package com.syni.mdd.yhd.common.all.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.syni.mdd.sjb.common.component.utils.common.utils.*;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddDistSys.CancelOrderDto;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddDistSys.RefundDto;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddDistSys.UseFxMoenyDto;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddDistSys.VerifyCodeDto;
import com.syni.mdd.sjb.common.component.utils.feign.service.mddDistSys.FxCenterService;
import com.syni.mdd.sjb.common.component.utils.redis.utils.RedisDistributedLockUtils;
import com.syni.mdd.sjb.common.component.utils.redis.utils.RedisTemplateUtils;
import com.syni.mdd.yhd.common.all.config.pay.wxPay.WxPayBean;
import com.syni.mdd.yhd.common.all.config.pay.wxPay.WxPayBeanFactory;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.controller.pay.aliPay.AliPayController;
import com.syni.mdd.yhd.common.all.dao.jpa.BmsDxOrderDao;
import com.syni.mdd.yhd.common.all.dao.jpa.BmsFxFirstDao;
import com.syni.mdd.yhd.common.all.dao.jpa.BmsFxSecondDao;
import com.syni.mdd.yhd.common.all.dto.reponseDto.order.OrderRefundDetailRpDto;
import com.syni.mdd.yhd.common.all.dto.reponseDto.order.UserOrderCallBackRpDto;
import com.syni.mdd.yhd.common.all.entity.*;
import com.syni.mdd.yhd.common.all.entity.activity.BmsBackCard;
import com.syni.mdd.yhd.common.all.entity.coupon.BmsFullCoupon;
import com.syni.mdd.yhd.common.all.entity.coupon.BmsUserReceCoupon;
import com.syni.mdd.yhd.common.all.entity.groupBuy.BmsThirdCode;
import com.syni.mdd.yhd.common.all.entity.groupBuy.BmsUserBargain;
import com.syni.mdd.yhd.common.all.entity.localLife.BmsLocalLifeGoodsVo;
import com.syni.mdd.yhd.common.all.entity.order.OrderCommitHolder;
import com.syni.mdd.yhd.common.all.entity.platformGood.BmsPlatformGood;
import com.syni.mdd.yhd.common.all.entity.user.BmsCustomer;
import com.syni.mdd.yhd.common.all.entity.user.BmsUser;
import com.syni.mdd.yhd.common.all.enums.ActivityEnums;
import com.syni.mdd.yhd.common.all.enums.groupBuy.BargainGroupBuyEnums;
import com.syni.mdd.yhd.common.all.enums.platformGood.PlatformGoodEnum;
import com.syni.mdd.yhd.common.all.listen.order.OrderEvent;
import com.syni.mdd.yhd.common.all.quartz.QuartzDo;
import com.syni.mdd.yhd.common.all.quartz.order.job.OrderCancelTimingJob;
import com.syni.mdd.yhd.common.all.service.activity.BmsBackCardService;
import com.syni.mdd.yhd.common.all.service.groupBuy.BmsUserBargainService;
import com.syni.mdd.yhd.common.all.service.impl.BaseService;
import com.syni.mdd.yhd.common.all.service.order.OrderCommitService;
import com.syni.mdd.yhd.common.all.service.pay.aiPay.AliPayService;
import com.syni.mdd.yhd.common.all.service.pay.wxPay.WxPayService;
import com.syni.mdd.yhd.common.all.service.platformGoods.BmsPlatformGoodService;
import com.syni.mdd.yhd.common.all.service.user.BmsCustomerService;
import com.syni.mdd.yhd.common.all.utils.RequestParamUtils;
import com.syni.mdd.yhd.common.all.utils.StringUtils;
import com.syni.mdd.yhd.common.all.utils.WebUtils;
import com.syni.mdd.yhd.common.all.utils.*;
import com.syni.mdd.yhd.common.all.vo.rp.dxOrder.GetMyOrderRpVo;
import com.syni.mdd.yhd.common.all.vo.rp.dxOrder.UserGetNewsOrderDisplayRpVo;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.collections.CollectionUtils;
import org.hibernate.Session;
import org.quartz.*;
import org.redisson.api.RBloomFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

;

/**
 * @className BmsUserOperationLogService
 * @description TOO
 * @Author cfx
 * @DATE 2019/4/9 12:04
 * @VERSION 1.0
 **/
@Service
@DependsOn("applicationContextHolder")
public class BmsDxOrderService extends BaseService<BmsDxOrder, Integer> {
    //高并发记录map,同个团购会进行阻塞
    private final Map<Integer,Integer> groupBuyMap = new ConcurrentHashMap<>();
    //团购退款,对团购张数进行锁定
    public final static Map<Integer, Integer> groupBuyRufundMap = new ConcurrentHashMap<>();
    private final Logger log = LoggerFactory.getLogger(getClass());
    ThreadLocal threadLocal = new ThreadLocal();
    public final static Map<Integer,OrderCommitService> orderCommitServiceMap = new HashMap();

    @PostConstruct
    public void init(){
        orderCommitServiceMap.put(Constants.PLATFORM_ORDER_TYPE, (OrderCommitService) SpringUtils.getBean("platformOrderServiceImpl"));
        orderCommitServiceMap.put(Constants.ONLINE_ORDER_TYPE,(OrderCommitService) SpringUtils.getBean("onlineOrderServiceImpl"));
        orderCommitServiceMap.put(Constants.FX_ORDER_TYPE,(OrderCommitService) SpringUtils.getBean("fenXiaoOrderServiceImpl"));
    }
    //线上买单
    final static int onlinePay = 1;
    //优惠买单
    final static int offerToPay = 2;
    //团购买单
    final static int groupBuyingPay = 3;
    //砍价订单
    final static int groupBuyBargainPay = 4;
    //本地生活订单
    final static int localLifePay = 5;
    //未支付
    final static int NO_PAY = 0;
    //可使用
    final static int CAN_USE = 1;
    //未支付
    final static int REFUND_OF = 2;
    //已支付
    final static int HAVE_REFUND = 3;
    //未支付
    final static int CANCEL_ORDER = 4;
    //已支付
    final static int HAVE_USE = 5;
    //统计
    final double defaultNum = 0d;
    final String groupByYear = "%Y-%m";
    final String groupByMonth = "%Y-%m-%d";

    @Autowired
    BmsDxOrderDao bmsDxOrderDao;

    @Autowired
    BmsUserService bmsUserService;

    @Autowired
    BmsDxCouponService bmsDxCouponService;

    @Autowired
    BmsBusinessService bmsBusinessService;

    @Autowired
    BmsDxGroupBuyService bmsDxGroupBuyService;

    @Autowired
    BmsDxGroupBuyUseService bmsDxGroupBuyUseService;

    @Autowired
    BmsDxOrderStatusService bmsDxOrderStatusService;

    @Autowired
    BmsUserBusinessService bmsUserBusinessService;

    @Autowired
    AliPayService alipayService;

    @Autowired
    BmsDxOrderService bmsDxOrderService;

    @Autowired
    BmsFullCouponService bmsFullCouponService;

    @Autowired
    BmsUserReceCouponService bmsUserReceCouponService;

    @Autowired
    BmsDxNewsService bmsDxNewsService;

    @Autowired
    ReOrderLogService reOrderLogService;

    @Autowired
    BmsBackCardService bmsBackCardService;

    @Autowired
    BmsThirdCodeService bmsThirdCodeService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    WxPayService wxPayService;

    @Autowired
    AliPayService aliPayService;

    @Autowired
    AliPayController aliPayController;

    @Autowired
    BmsUserBargainService bmsUserBargainService;

    @Autowired
    BmsLocalLifeGoodsService bmsLocalLifeGoodsService;

    @Autowired
    BmsLocalLifeService bmsLocalLifeService;

    @Autowired
    BmsUserLifeInfoService bmsUserLifeInfoService;

    @Autowired
    BmsLocalLifeGoodsRelationService lifeGoodsRelationService;

    @Autowired
    BmsPlatformGoodService bmsPlatformGoodService;

    @Autowired
    EntityManager entityManager;

    @Autowired
    BmsCustomerService bmsCustomerService;

    @Autowired
    FxCenterService fxCenterService;

    @Autowired
    ImgPrefixService imgPrefixService;

    @Autowired
    BmsFxFirstDao bmsFxFirstDao;

    @Autowired
    BmsFxSecondDao bmsFxSecondDao;

    @Override
    public BmsDxOrderDao getBaseDao() {
        return bmsDxOrderDao;
    }

    public Map<Integer, Integer> getGroupBuyMap() {
        return groupBuyMap;
    }

    public static Map<Integer, Integer> getGroupBuyRufundMap() {
        return groupBuyRufundMap;
    }

    public Map<String,Object> orderCommit(Map<String,Object> paramsMap) {
        final int FIVE_FULL_COUPON = 5;
        final int EIGHT_FULL_COUPON = 8;
        final Map<Integer,Integer> fullCouponUseNumLimitMap = new HashMap<Integer,Integer>(){{
            put(FIVE_FULL_COUPON,80);
            put(EIGHT_FULL_COUPON,50);
        }};
        String userIdentify = paramsMap.get("userIdentify").toString();
        Integer businessId = Integer.parseInt(paramsMap.get("businessId").toString());
        Integer userId = Integer.parseInt(userIdentify);
        Integer orderType = Integer.parseInt(paramsMap.get("orderType").toString());
        Integer userFullCouponId = null;
        if(paramsMap.containsKey("userFullCouponId") && StringUtils.checkNullAndEmpty(paramsMap.get("userFullCouponId"))){
            userFullCouponId = Integer.parseInt(paramsMap.get("userFullCouponId").toString());
        }
        //Integer qs = Integer.parseInt(paramsMap.get("qs").toString());
        BmsDxOrder bmsDxOrder = new BmsDxOrder();
        Date nowTime = new Date();
        Optional<BmsBusiness> businessOptional = bmsBusinessService.getBaseDao().findById(businessId);
        if(!businessOptional.isPresent()){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST,ResultMsg.CODE_BUSINESS_NO_EXIST);
        }
        BmsBusiness business = businessOptional.get();
        BmsFullCoupon bmsFullCoupon = null;
        BmsUserReceCoupon bmsUserReceCoupon = null;
        if(userFullCouponId != null){
            Optional<BmsUserReceCoupon> bmsUserReceCouponOptional = bmsUserReceCouponService.getBaseDao().findById(userFullCouponId);
            if(!bmsUserReceCouponOptional.isPresent()){
                return ResultMapHelper.result(ResultCode.CODE_FULL_COUPON_IS_NO_EXIST,ResultMsg.CODE_FULL_COUPON_IS_NO_EXIST);
            }
            bmsUserReceCoupon = bmsUserReceCouponOptional.get();
            if(bmsUserReceCoupon.getStatus() == Constants.COMMON_FLAG_TRUE_INT){
                return ResultMapHelper.result(ResultCode.CODE_FULL_COUPON_IS_USE,ResultMsg.CODE_FULL_COUPON_IS_USE);
            }
            if(bmsUserReceCoupon.getBusinessId().intValue() != business.getId().intValue()){
                return ResultMapHelper.result(ResultCode.CODE_FULL_COUPON_IS_NO_BELONG,ResultMsg.CODE_FULL_COUPON_IS_NO_BELONG);
            }
            Integer expireTime = DateTimeUtils.converDateToInterger(DateTimeUtils.addDay(bmsUserReceCoupon.getExpireTime(),1));
            if(DateTimeUtils.converDateToInterger(nowTime).intValue() > expireTime.intValue()){
                return ResultMapHelper.result(ResultCode.CODE_FULL_COUPON_IS_EXPIRE,ResultMsg.CODE_FULL_COUPON_IS_EXPIRE);
            }
            bmsFullCoupon = bmsUserReceCoupon.getBmsFullCoupon();
            if(bmsFullCoupon == null){
                return ResultMapHelper.result(ResultCode.CODE_FULL_COUPON_IS_USE,ResultMsg.CODE_FULL_COUPON_IS_USE);
            }
            //判断是否超过小时限制
            String[] fullRule = bmsFullCoupon.getFullRule().split("_");
            String redisKey = Constants.REDIS_KEY_FULL_COUPON_USE_NUM + bmsFullCoupon.getId();
            if(redisTemplate.hasKey(redisKey)){
                Integer useNum = Integer.parseInt(redisTemplate.opsForValue().get(redisKey).toString());
                Integer fullMoney = Integer.parseInt(fullRule[1]);
                if(fullCouponUseNumLimitMap.containsKey(fullMoney)) {
                    if (useNum.intValue() >= fullCouponUseNumLimitMap.get(fullMoney).intValue()) {
                        return ResultMapHelper.result(ResultCode.CODE_FULL_COUPON_IS_MORE, ResultMsg.CODE_FULL_COUPON_IS_MORE);
                    }
                }
            }
        }
        BmsDxGroupBuy bmsDxGroupBuy = null;
        Double discountConsum = 0d;
        OrderCommitHolder orderCommitHolder = new OrderCommitHolder();
        if(orderType == onlinePay){
            Map<String,Object> checkMap = RequestParamUtils.checkParams(paramsMap,"totalConsum","actualConsum");
            if(!(checkMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString()))){
                return checkMap;
            }
            Double totalConsum = Double.parseDouble(paramsMap.get("totalConsum").toString());
            Double actualConsum = totalConsum;
            Double shopConsum = ArithUtil.mul(actualConsum,Constants.SEETLE_LINES);
            Double settleMoney = ArithUtil.mul(actualConsum,Constants.SEETLE_LINES);
            if(bmsFullCoupon != null){
                //满减规则
                String[] fullRule = bmsFullCoupon.getFullRule().split("_");
                //触发金额
                Double fullMoney = Double.parseDouble(fullRule[0]);
                //是否有无门槛
                if(bmsFullCoupon.getIsThhold() == Constants.FULL_COUPON_HAVE_THHOLD) {
                    if (totalConsum < fullMoney) {
                        return ResultMapHelper.result(ResultCode.CODE_FULL_COUPON_ILLEGAL, ResultMsg.CODE_FULL_COUPON_ILLEGAL);
                    }
                }
                //满减额度
                Double reduction = Double.parseDouble(fullRule[1]);
                //优惠金额
                discountConsum = reduction;
                //用户实付金额
                actualConsum = ArithUtil.sub(totalConsum,reduction);
                //商家能获得的钱
                shopConsum = ArithUtil.mul(totalConsum,Constants.SEETLE_LINES);
                //程序分账金额
                settleMoney = ArithUtil.sub(shopConsum,reduction);
                bmsDxOrder.setFullCouponId(userFullCouponId);
                bmsUserReceCoupon.setStatus(Constants.COMMON_FLAG_TRUE_INT);
                bmsUserReceCoupon.setUseTime(nowTime);
            }
            if(settleMoney > 0d) {
                //shopConsum = ArithUtil.add(shopConsum,settleMoney);
                settleMoney = 0d;
            }
            bmsDxOrder.setTotalConsum(totalConsum);
            bmsDxOrder.setActualConsum(actualConsum);
            bmsDxOrder.setSettleMoney(settleMoney);
            bmsDxOrder.setShopConsum(shopConsum);
        }else if(orderType == offerToPay){
            Map<String,Object> checkMap = RequestParamUtils.checkParams(paramsMap, "totalConsum",
                    "actualConsum","noJoinConsum","couponId");
            if(!(checkMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString()))){
                return checkMap;
            }
            Double totalConsum = Double.parseDouble(paramsMap.get("totalConsum").toString());
            Double actualConsum = Double.parseDouble(paramsMap.get("actualConsum").toString());
            Double noJoinConsum = Double.parseDouble(paramsMap.get("noJoinConsum").toString());
            Integer couponId = Integer.parseInt(paramsMap.get("couponId").toString());
            Optional<BmsDxCoupon> bmsDxCouponOp = bmsDxCouponService.getBaseDao().findById(couponId);
            if(!bmsDxCouponOp.isPresent()){
                return ResultMapHelper.result(ResultCode.CODE_ORDER_ONLINEPAY_NO_EXIST,ResultMsg.CODE_ORDER_ONLINEPAY_NO_EXIST);
            }
            BmsDxCoupon bmsDxCoupon = bmsDxCouponOp.get();
            if(bmsDxCoupon.getUseNum() != Constants.COMMON_FLAG_FALSE_INT){
                //有使用次数限制，查询当前用户是否达到使用次数
                Integer num = bmsDxOrderDao.countUserUseCouponNum(userId,couponId);
                System.out.println(num);
                if(num.intValue() >= bmsDxCoupon.getUseNum()){
                    return ResultMapHelper.result(ResultCode.CODE_ORDER_ONLINEPAY_MAX,ResultMsg.CODE_ORDER_ONLINEPAY_MAX);
                }
            }
            double calAmount = ArithUtil.sub(totalConsum,noJoinConsum);
            double discount = ArithUtil.div(Double.parseDouble(bmsDxCoupon.getPayContent()),10d);
            double discountMoney = ArithUtil.mul(calAmount,discount);
            actualConsum = ArithUtil.add(noJoinConsum,discountMoney);
            Double shopConsum = ArithUtil.mul(actualConsum,Constants.SEETLE_LINES);
            Double settleMoney = ArithUtil.mul(actualConsum,Constants.SEETLE_LINES);
            Double preferentialMoney = calAmount - discountMoney;
            if(bmsFullCoupon != null){
                //满减规则
                String[] fullRule = bmsFullCoupon.getFullRule().split("_");
                //触发金额
                Double fullMoney = Double.parseDouble(fullRule[0]);
                if(bmsFullCoupon.getIsThhold() == Constants.FULL_COUPON_HAVE_THHOLD) {
                    if(actualConsum < fullMoney){
                        return ResultMapHelper.result(ResultCode.CODE_FULL_COUPON_ILLEGAL,ResultMsg.CODE_FULL_COUPON_ILLEGAL);
                    }
                }
                //满减额度
                Double reduction = Double.parseDouble(fullRule[1]);
                //优惠金额
                discountConsum = reduction;
                //原本需要分给商家的钱
                shopConsum = ArithUtil.mul(actualConsum,Constants.SEETLE_LINES);
                //用户实付金额
                actualConsum = ArithUtil.sub(actualConsum,reduction);
                //商家所获得金额
                settleMoney = ArithUtil.sub(shopConsum,reduction);
                bmsDxOrder.setFullCouponId(userFullCouponId);
                bmsUserReceCoupon.setStatus(Constants.COMMON_FLAG_TRUE_INT);
                bmsUserReceCoupon.setUseTime(nowTime);
            }
            if(settleMoney > 0d) {
                //shopConsum = ArithUtil.add(shopConsum,settleMoney);
                settleMoney = 0d;
            }
            bmsDxOrder.setTotalConsum(totalConsum);
            bmsDxOrder.setActualConsum(actualConsum);
            bmsDxOrder.setNoJoinConsum(noJoinConsum);
            bmsDxOrder.setBmsCouponId(couponId);
            bmsDxOrder.setSettleMoney(settleMoney);
            bmsDxOrder.setShopConsum(shopConsum);
            bmsDxOrder.setPreferentialMoney(preferentialMoney);
        }else if(orderType == groupBuyingPay){
            Map<String,Object> checkMap = RequestParamUtils.checkParams(paramsMap, "groupBuyNum","groupBuyId");
            if(!(checkMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString()))){
                return checkMap;
            }
            Integer groupBuyId = Integer.parseInt(paramsMap.get("groupBuyId").toString());
            Integer groupBuyNum = Integer.parseInt(paramsMap.get("groupBuyNum").toString());
            bmsDxGroupBuy =  bmsDxGroupBuyService.getGroupBuyById(groupBuyId);
            if(bmsDxGroupBuy == null) {
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST_GROUP_BUY, ResultMsg.CODE_BUSINESS_NO_EXIST_GROUP_BUY);
            }
            //判断该团购券是否属于商家
            if(bmsDxGroupBuy.getBusinessId() != businessId.intValue()){
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_BELONG,ResultMsg.CODE_BUSINESS_NO_BELONG);
            }
            //是否超过团购券限制购买数量
            if(bmsDxGroupBuy.getLimitBuyNum() != null){
                //查询当前用户已经买了多少张这个团购券
                Integer userAlreadyBuyNum = bmsDxGroupBuyUseService.getUserBuyNum(userId,bmsDxGroupBuy.getId());
                if(groupBuyNum > (bmsDxGroupBuy.getLimitBuyNum() - userAlreadyBuyNum)){
                    return ResultMapHelper.result(ResultCode.CODE_BUSINESS_OVER_NUM,ResultMsg.CODE_BUSINESS_OVER_NUM);
                }
            }
            if(bmsDxGroupBuy.getSellInventory() != null){
                final int MAX_GET = 10;
                int count = 0;
                while (count < MAX_GET) {
                    try {
                        Integer getLock = groupBuyMap.putIfAbsent(bmsDxGroupBuy.getId(), Constants.COMMON_FLAG_TRUE_INT);
                        if (getLock == null) {
                            break;
                        }
                        count++;
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        log.error(e.getMessage(),e);
                    }
                    log.info("团购线程拿锁失败.......");
                }
                if(count >= MAX_GET){
                    return ResultMapHelper.result(ResultCode.CODE_ORDER_PLACE_FAIL,ResultMsg.CODE_ORDER_PLACE_FAIL);
                }
                Integer num = bmsDxGroupBuyService.getBaseDao().countGroupBuySellNum(groupBuyId);
                if (groupBuyNum > num) {
                    return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NOT_ENOUGH, ResultMsg.CODE_BUSINESS_NOT_ENOUGH);
                }
                bmsDxGroupBuy.setSellInventory(num - groupBuyNum);
            }
            Double totalConsum = ArithUtil.mul(groupBuyNum,bmsDxGroupBuy.getGroupPrice());
            Double actualConsum = totalConsum;
            if(bmsFullCoupon != null){
                //满减规则
                String[] fullRule = bmsFullCoupon.getFullRule().split("_");
                //触发金额
                Double fullMoney = Double.parseDouble(fullRule[0]);
                if(bmsFullCoupon.getIsThhold() == Constants.FULL_COUPON_HAVE_THHOLD) {
                    if(actualConsum < fullMoney){
                        return ResultMapHelper.result(ResultCode.CODE_FULL_COUPON_ILLEGAL,ResultMsg.CODE_FULL_COUPON_ILLEGAL);
                    }
                }
                //满减额度
                Double reduction = Double.parseDouble(fullRule[1]);
                //优惠金额
                discountConsum = reduction;
                //用户实付金额
                actualConsum = ArithUtil.sub(actualConsum,reduction);
                bmsDxOrder.setFullCouponId(userFullCouponId);
                bmsUserReceCoupon.setStatus(Constants.COMMON_FLAG_TRUE_INT);
                bmsUserReceCoupon.setUseTime(nowTime);
            }
            bmsDxOrder.setBmsGroupBuyId(bmsDxGroupBuy.getId());
            bmsDxOrder.setGroupBuyNum(groupBuyNum);
            bmsDxOrder.setTotalConsum(totalConsum);
            bmsDxOrder.setActualConsum(actualConsum);
            bmsDxOrder.setBmsDxGroupBuy(bmsDxGroupBuy);

        }else {
            return ResultMapHelper.result(ResultCode.CODE_ORDER_TYPE_ERROR,ResultMsg.CODE_ORDER_TYPE_ERROR);
        }
        //优惠金额
        if(bmsDxOrder.getActualConsum() <= 0d){
            bmsDxOrder.setActualConsum(0d);
        }
        bmsDxOrder.setDiscountConsum(discountConsum);
        bmsDxOrder.setBmsUserId(userId);
        bmsDxOrder.setBmsBusinessId(businessId);
        bmsDxOrder.setOrderType(orderType);
        bmsDxOrder.setOrderNo(OrderUtils.getOrderNo(businessId));
        bmsDxOrder.setVendorName(business.getVendorName());
        bmsDxOrder.setIsDelete(Constants.COMMON_FLAG_FALSE_INT);
        final int MAX_REPEAT = 5;
        //重复下单5次
        int orderNum = 0;
        while (orderNum < MAX_REPEAT){
            try {
                bmsDxOrderService.placeTheOrder(bmsDxOrder,bmsDxGroupBuy,bmsUserReceCoupon,null,orderCommitHolder);
                break;
            }catch (Exception e){
                log.info(e.toString());
                orderNum++;
                bmsDxOrder.setOrderNo(OrderUtils.getOrderNo(businessId));
            }
        }
        if(orderNum >= MAX_REPEAT){
            return ResultMapHelper.result(ResultCode.CODE_ORDER_PLACE_FAIL,ResultMsg.CODE_ORDER_PLACE_FAIL);
        }
        bmsDxOrder.setTimingCancelTime(DateTimeUtils.addMinutes(nowTime,Constants.AUTO_CANCEL_ORDER_MINUTE));
        doOrderCancelTiming(OrderCancelTimingJob.class,bmsDxOrder.getTimingCancelTime(),bmsDxOrder);
        //处理订单后置逻辑
        orderHandAfterLogic(bmsDxOrder);
        if(bmsDxOrder.getFullCouponId() != null){
            orderActivityCount(bmsFullCoupon);
        }
        bmsDxOrderDao.save(bmsDxOrder);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("orderId",bmsDxOrder.getId());
        resultMap.put("orderNo",bmsDxOrder.getOrderNo());
        resultMap.put("newTime",bmsDxOrder.getNewTime());
        resultMap.put("timingCancelTime",bmsDxOrder.getTimingCancelTime());
        resultMap.put("bmsUserReceCoupon",bmsUserReceCoupon);
        return ResultMapHelper.success(resultMap,"下单成功");
    }

    public void orderHandAfterLogic(BmsDxOrder bmsDxOrder){
        if (bmsDxOrder.getActualConsum() <= 0d) {
            Date nowTime = new Date();
            bmsDxOrder.setPayNo(String.valueOf(System.currentTimeMillis()));
            if (alipayService.orderPayHand("no can pay order",bmsDxOrder,nowTime)) {
                bmsDxOrder.setPayTime(nowTime);
            }
        }
    }

    public void orderActivityCount(BmsFullCoupon bmsFullCoupon){
        if(bmsFullCoupon != null) {
            String redisKey = Constants.REDIS_KEY_FULL_COUPON_USE_NUM + bmsFullCoupon.getId();
            if (!redisTemplate.hasKey(redisKey)) {
                redisTemplate.opsForValue().set(redisKey, 1, 1, TimeUnit.HOURS);
            } else {
                synchronized (this) {
                    Integer useNum = Integer.parseInt(redisTemplate.opsForValue().get(redisKey).toString());
                    long restTime = redisTemplate.getExpire(redisKey);
                    redisTemplate.opsForValue().set(redisKey, useNum + 1, restTime, TimeUnit.SECONDS);
                }
            }
        }
    }

    @Transactional
    public void placeTheOrder(BmsDxOrder bmsDxOrder,BmsDxGroupBuy bmsDxGroupBuy,BmsUserReceCoupon bmsUserReceCoupon,
                              BmsBackCard bmsBackCard,OrderCommitHolder orderCommitHolder){
        if(bmsDxGroupBuy != null){
            bmsDxGroupBuyService.getBaseDao().save(bmsDxGroupBuy);
        }
        if(bmsUserReceCoupon != null){
            bmsUserReceCouponService.getBaseDao().save(bmsUserReceCoupon);
        }
        if(bmsBackCard != null){
            bmsBackCardService.getBaseDao().save(bmsBackCard);
        }
        if(orderCommitHolder.getBmsUserBargain() != null){
            bmsUserBargainService.getBaseDao().save(orderCommitHolder.getBmsUserBargain());
        }

        handOrderMoney(bmsDxOrder);
        bmsDxOrderDao.save(bmsDxOrder);
        handldOrderPost(bmsDxOrder);
    }

    private void handOrderMoney(BmsDxOrder bmsDxOrder) {
        bmsDxOrder.setActualConsum(ArithUtil.round(bmsDxOrder.getActualConsum(),2));
        bmsDxOrder.setTotalConsum(ArithUtil.round(bmsDxOrder.getTotalConsum(),2));
        bmsDxOrder.setDiscountConsum(ArithUtil.round(bmsDxOrder.getDiscountConsum(),2));
        bmsDxOrder.setShopConsum(ArithUtil.round(bmsDxOrder.getShopConsum(),2));
        bmsDxOrder.setNoJoinConsum(ArithUtil.round(bmsDxOrder.getNoJoinConsum(),2));
        bmsDxOrder.setSettleMoney(ArithUtil.round(bmsDxOrder.getSettleMoney(),2));
    }

    /**
     * @Description 下单成功后续操作
     * @Author: cfx
     * @Date: 2019/7/30
     */
    public void handldOrderPost(BmsDxOrder bmsDxOrder) {
        //往订单状态表插入一条记录
        updateBmsDxOrderStatus(bmsDxOrder);
    }

    public BmsDxOrderStatus updateBmsDxOrderStatus(BmsDxOrder bmsDxOrder){
        BmsDxOrderStatus bmsDxOrderStatus = new BmsDxOrderStatus();
        bmsDxOrderStatus.setOrderType(bmsDxOrder.getOrderType());
        bmsDxOrderStatus.setNewTime(bmsDxOrder.getNewTime());
        bmsDxOrderStatus.setOrderId(bmsDxOrder.getId());
        bmsDxOrderStatus.setUserId(bmsDxOrder.getBmsUserId());
        bmsDxOrderStatus.setStatus(Constants.NO_PAY);
        bmsDxOrderStatus.setBusinessId(bmsDxOrder.getBmsBusinessId());
        bmsDxOrderStatus.setVendorName(bmsDxOrder.getVendorName());
        /*if(bmsDxOrder.getOrderType() == Constants.GROUP_BUY_ORDER_TYPE) {
            BmsDxGroupBuy bmsDxGroupBuy = bmsDxOrder.getBmsDxGroupBuy();
            bmsDxOrderStatus.setGroupBuyType(bmsDxGroupBuy.getGroupType());
        }*/
        bmsDxOrderStatusService.getBaseDao().save(bmsDxOrderStatus);
        return bmsDxOrderStatus;
    }

    /**
     * @Description 定时取消订单
     * @Author: cfx
     * @Date: 2019/8/14
     */
    public void doOrderCancelTiming(Class classes,Date startDate,BmsDxOrder bmsDxOrder){
        //延长5分钟
        //startDate = DateTimeUtils.addMinutes(startDate,Constants.AUTO_CANCEL_ORDER_MINUTE_EXTEND);
        Integer orderId = bmsDxOrder.getId();
        String jobName = Constants.ORDER_JOB_NAME + orderId;
        String triggerName = Constants.ORDER_TRI_NAME + orderId;
        try {
            JobDetail job1 = JobBuilder.newJob(classes)
                    .withIdentity(jobName,Constants.ORDER_DEFAULT_JOB_GROUOP)
                    .build();
            job1.getJobDataMap().put("bmsDxOrder",bmsDxOrder);
            SimpleTrigger trigger1 = (SimpleTrigger) TriggerBuilder.newTrigger()
                    .withIdentity(triggerName, Constants.ORDER_DEFAULT_TRI_GROUOP)
                    //.forJob("jog1", "group1")                 // identify job with name, group strings
                    .startAt(startDate)
                    .build();
            QuartzDo.addJobToScheduler(job1,trigger1);
            QuartzDo.getScheduler().start();
        } catch (SchedulerException e) {
            log.error(e.getMessage(),e);
        }
    }

    public Map<String,Object> checkOrderEffective(Integer orderId,String orderNo){
        Optional<BmsDxOrder> bmsDxOrderOptional =  bmsDxOrderDao.findById(orderId);
        if(!bmsDxOrderOptional.isPresent()){
            return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_EXIST,ResultMsg.CODE_ORDER_NO_EXIST);
        }
        BmsDxOrder bmsDxOrder = bmsDxOrderOptional.get();
        if(!bmsDxOrder.getOrderNo().equals(orderNo)){
            return ResultMapHelper.result(ResultCode.CODE_ORDER_ID_NOMATCH_NO, ResultMsg.CODE_ORDER_ID_NOMATCH_NO);
        }
        return ResultMapHelper.success(bmsDxOrder);
    }

    public Map<String,Object> orderCallBack(Map<String,Object> paramsMap){
        Integer userId = Integer.parseInt(paramsMap.get("userIdentify").toString());
        Integer orderId = Integer.parseInt(paramsMap.get("orderId").toString());
        String orderNo = paramsMap.get("orderNo").toString();
        Map<String,Object> checkMap = checkOrderEffective(orderId,orderNo);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        BmsDxOrder bmsDxOrder = (BmsDxOrder) checkMap.get("data");
        if(bmsDxOrder.getBmsUserId() != userId.intValue()){
            return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_BELONG,ResultMsg.CODE_ORDER_NO_BELONG);
        }
        //判断订单是否支付
        Set<Integer> statusIn = new HashSet<>();
        statusIn.add(Constants.PAY_COMPLETE);
        if(bmsDxOrder.getOrderType() == Constants.GROUP_BUY_ORDER_TYPE
                || bmsDxOrder.getOrderType() == Constants.GROUP_BUY_BARGAIN_ORDER_TYPE
                || bmsDxOrder.getOrderType() == Constants.FX_ORDER_TYPE){
            statusIn.add(Constants.ALREADY_USE);
        }else if(bmsDxOrder.getOrderType() == Constants.LOCAL_LIFE_ORDER_TYPE){
            statusIn.add(Constants.WAIT_GET);
        }else if(bmsDxOrder.getOrderType() == Constants.PLATFORM_ORDER_TYPE){
            statusIn.add(Constants.WAIT_GET);
        }
        List<BmsDxOrderStatus> bmsDxOrderStatus = bmsDxOrderStatusService.getBaseDao().findByOrderIdAndStatusIn(orderId,statusIn);
        if(!(bmsDxOrderStatus != null && bmsDxOrderStatus.size() > 0)) {
            boolean noConfirm = true;
            if (bmsDxOrder.getPayWay() != null && bmsDxOrder.getPayWay() == Constants.WX_PAY) {
                //自动查询
                Map<String, Object> resultMap = wxPayService.orderQuery(bmsDxOrder.getOrderNo(), WxPayBeanFactory.MIN_APP_CHANNEL);
                if (resultMap.containsKey("isPay") && resultMap.get("isPay").toString().equals(Constants.COMMON_FLAG_TRUE)) {
                    noConfirm = false;
                    Date payTime = (Date) resultMap.get("date");
                    String tradeNo = resultMap.get("tradeNo").toString();
                    if (alipayService.orderPayHand("no can pay order", bmsDxOrder, payTime)) {
                        bmsDxOrder.setPayTime(payTime);
                        bmsDxOrder.setTransactionId(tradeNo);
                        bmsDxOrderService.getBaseDao().save(bmsDxOrder);
                    }
                }else if (resultMap.containsKey("isPay") && resultMap.get("isPay").toString().equals(Constants.COMMON_FLAG_FALSE)) {
                    return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_PAY, ResultMsg.CODE_ORDER_NO_PAY);
                }
            } else if (bmsDxOrder.getPayWay() != null && bmsDxOrder.getPayWay() == Constants.ALI_PAY) {
                Map<String, Object> resultMap = aliPayService.appOrderQuery(bmsDxOrder.getOrderNo(), bmsDxOrder.getActualConsum());
                if (!(resultMap.containsKey("isPay") && resultMap.get("isPay").toString().equals(Constants.COMMON_FLAG_TRUE))) {
                    return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_PAY, ResultMsg.CODE_ORDER_NO_PAY);
                }
                Date payTime = (Date) resultMap.get("date");
                String tradeNo = resultMap.get("tradeNo").toString();
                if (alipayService.orderPayHand("no can pay order", bmsDxOrder, payTime)) {
                    bmsDxOrder.setPayTime(payTime);
                    bmsDxOrder.setPayNo(tradeNo);
                    bmsDxOrderService.getBaseDao().save(bmsDxOrder);
                }
            }
            if (noConfirm) {
                //网络原因回调慢,尝试等待获取
                final int GET_MAX = 5;
                int count = 0;
                while (true) {
                    try {
                        if (count == GET_MAX) {
                            return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_PAY, ResultMsg.CODE_ORDER_NO_PAY);
                        }
                        bmsDxOrderStatus = bmsDxOrderStatusService.getBaseDao().findByOrderIdAndStatusIn(orderId, statusIn);
                        if (bmsDxOrderStatus != null && bmsDxOrderStatus.size() > 0) {
                            break;
                        }
                        Thread.sleep(1000);
                        count++;
                    } catch (InterruptedException e) {
                        log.error("orderCallback wait error", e);
                    }
                }
            }
        }
        Integer orderType = bmsDxOrder.getOrderType();
        BmsBusiness business = bmsBusinessService.getBusinessById(bmsDxOrder.getBmsBusinessId());
        if(business == null){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST,ResultMsg.CODE_BUSINESS_NO_EXIST);
        }
        UserOrderCallBackRpDto userOrderCallBackRpDto = new UserOrderCallBackRpDto();
        userOrderCallBackRpDto.setOrderId(orderId);
        userOrderCallBackRpDto.setOrderNo(bmsDxOrder.getOrderNo());
        userOrderCallBackRpDto.setNewTime(bmsDxOrder.getNewTime());
        userOrderCallBackRpDto.setOrderType(bmsDxOrder.getOrderType());
        userOrderCallBackRpDto.setVendorName(business.getVendorName());
        if(orderType == onlinePay){
            //返回回调信息
            userOrderCallBackRpDto.setTotalConsum(bmsDxOrder.getTotalConsum());
            userOrderCallBackRpDto.setActualConsum(bmsDxOrder.getActualConsum());
        }else if(orderType == offerToPay){
            //返回回调信息
            userOrderCallBackRpDto.setTotalConsum(bmsDxOrder.getTotalConsum());
            userOrderCallBackRpDto.setActualConsum(bmsDxOrder.getActualConsum());
        }else if(orderType.equals(Constants.GROUP_BUY_ORDER_TYPE) || orderType.equals(Constants.FX_ORDER_TYPE)){
            BmsDxGroupBuy bmsDxGroupBuy = bmsDxOrder.getBmsDxGroupBuy();
            userOrderCallBackRpDto.setGroupName(bmsDxGroupBuy.getGroupName());
            List<String> groupByCodes = new ArrayList<>();
            List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = bmsDxGroupBuyUseService.getGroupByCode(bmsDxOrder.getId(),Constants.COMMON_FLAG_FALSE_INT);
            if(bmsDxGroupBuy.getGroupType() != null && bmsDxGroupBuy.getGroupType() == Constants.COMMON_FLAG_TRUE_INT){
                bmsDxGroupBuyUses = bmsDxGroupBuyUseService.getGroupByCode(bmsDxOrder.getId(),Constants.GROUP_ALREADY_USE);
            }
            if(CollectionUtils.isNotEmpty(bmsDxGroupBuyUses)){
                bmsDxGroupBuyUseService.postHandleQrCodeText(bmsDxGroupBuyUses);
                for(BmsDxGroupBuyUse bmsDxGroupBuyUse : bmsDxGroupBuyUses){
                    groupByCodes.add(bmsDxGroupBuyUse.getGroupBuyCode());
                }
                userOrderCallBackRpDto.setQrCodeText(bmsDxGroupBuyUses.get(0).getQrCodeText());
            }
            userOrderCallBackRpDto.setGroupPayCodes(groupByCodes);
            userOrderCallBackRpDto.setBmsDxGroupBuy(bmsDxOrder.getBmsDxGroupBuy());
        }else if(orderType == Constants.GROUP_BUY_BARGAIN_ORDER_TYPE){
            BmsDxGroupBuy bmsDxGroupBuy = bmsDxOrder.getBmsDxGroupBuy();
            userOrderCallBackRpDto.setGroupName(bmsDxGroupBuy.getGroupName());
            List<String> groupByCodes = new ArrayList<>();
            List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = bmsDxGroupBuyUseService.getGroupByCode(bmsDxOrder.getId(),Constants.COMMON_FLAG_FALSE_INT);
            if(bmsDxGroupBuyUses != null && bmsDxGroupBuyUses.size() > 0){
                bmsDxGroupBuyUseService.postHandleQrCodeText(bmsDxGroupBuyUses);
                for(BmsDxGroupBuyUse bmsDxGroupBuyUse : bmsDxGroupBuyUses){
                    groupByCodes.add(bmsDxGroupBuyUse.getGroupBuyCode());
                }
                userOrderCallBackRpDto.setQrCodeText(bmsDxGroupBuyUses.get(0).getQrCodeText());
            }
            userOrderCallBackRpDto.setGroupPayCodes(groupByCodes);
            userOrderCallBackRpDto.setBmsDxGroupBuy(bmsDxOrder.getBmsDxGroupBuy());
        }
        if(bmsDxOrder.getFullCouponId() != null){
            BmsUserReceCoupon bmsUserReceCoupon = bmsUserReceCouponService.getBaseDao().findByIdAndStatus(bmsDxOrder.getFullCouponId(),Constants.COMMON_FLAG_TRUE_INT);
            userOrderCallBackRpDto.setBmsUserReceCoupon(bmsUserReceCoupon);
        }
        return ResultMapHelper.success(userOrderCallBackRpDto,ResultMsg.MSG_GET_SUCCESS);
    }

    public Map<String,Object> getBussinessYearOrder(Integer businessId,Integer showNum,String endDate){
        showNum = showNum + 1;
        LinkedList<String> yearDateList = getFrontMonth(showNum,endDate);
        String nextSearchDate = yearDateList.getLast();
        yearDateList.removeLast();
        if(yearDateList.size() == 0){
            return ResultMapHelper.failure("获取失败！");
        }
        Integer startTime = (int)(DateTimeUtils.converStrToTimestamp(String.format("%s-01 00:00:00",yearDateList.getLast())).getTime() / 1000);
        Date firstDate = DateTimeUtils.converStringToDate(String.format("%s-01 00:00:00",yearDateList.getFirst()));
        Date lastDay = DateTimeUtils.getLastDayOfMonth(firstDate);
        Integer endTime = (int)(lastDay.getTime() / 1000);
        Map<String,Double> countYearMap = new LinkedHashMap<>();
        for(String yearDate : yearDateList){
            countYearMap.put(yearDate,defaultNum);
        }
        List<Map<String, Object>> countResult = bmsDxOrderDao.GroupByOrderTime(startTime, endTime, businessId,groupByYear);
        return ResultMapHelper.success(handCountResult(countResult,countYearMap,nextSearchDate),"获取成功！");
    }

    public LinkedList<String> getFrontMonth(Integer showNum,String selfDate){
        LinkedList<String> yearDateList = new LinkedList<>();
        Date date = new Date();
        if(selfDate != null){
            date = DateTimeUtils.converStringToDate(String.format("%s-01",selfDate));
        }
        for(int ii=0;ii < showNum;ii++){
            yearDateList.add(DateTimeUtils.getYearMonthStr(date,-ii));
        }
        //获取往后n个月
        return yearDateList;
    }


    public Map<String, Object> getBussinessMonthOrder(Integer businessId, Integer showNum, String searchMonth, String endDate) {
        showNum = showNum + 1;
        LinkedList<String> monthDateList = getFrontDay(searchMonth,showNum,endDate);
        String nextSearchDate = monthDateList.getLast();
        monthDateList.removeLast();
        if(monthDateList.size() == 0){
            return ResultMapHelper.failure("获取失败！");
        }
        Map<String,Double> countMonthMap = new LinkedHashMap<>();
        Integer startTime = (int)(DateTimeUtils.converStrToTimestamp(String.format("%s 00:00:00",monthDateList.getLast())).getTime() / 1000);
        Integer endTime = (int)(DateTimeUtils.converStrToTimestamp(String.format("%s 23:59:59",monthDateList.getFirst())).getTime() / 1000);
        for(String yearDate : monthDateList){
            countMonthMap.put(yearDate,defaultNum);
        }
        List<Map<String, Object>> countResult = bmsDxOrderDao.GroupByOrderTime(startTime, endTime, businessId,groupByMonth);
        System.out.println(countResult);
        return ResultMapHelper.success(handCountResult(countResult,countMonthMap,nextSearchDate),"获取成功！");
    }

    public LinkedList<String> getFrontDay(String dateIndex,Integer showNum,String selfDate){
        LinkedList<String> monthDateList = new LinkedList<>();
        Date date = new Date();
        Integer nowMonth = DateTimeUtils.getMonth(date);
        Date dateIndexDate = DateTimeUtils.converStringToDate(String.format("%s-01",dateIndex));
        Integer searchMoth = DateTimeUtils.getMonth(dateIndexDate);
        //获取当月天数
        Integer startIndex = DateTimeUtils.getDay(DateTimeUtils.getLastDayOfMonth(dateIndexDate));
        if(selfDate != null) {
           startIndex = DateTimeUtils.getDay(DateTimeUtils.converStringToDate(selfDate));
        }else {
            if (nowMonth == searchMoth) {
                startIndex = DateTimeUtils.getDay(date);
            }
        }
        for(int ii = 0;ii < showNum;ii++){
            System.out.println(DateTimeUtils.getMonthDayStr(dateIndexDate,startIndex));
            monthDateList.add(DateTimeUtils.getMonthDayStr(dateIndexDate,startIndex));
            startIndex--;
        }
        return monthDateList;
    }

    public Map<String,Object> handCountResult(List<Map<String, Object>> countResult,Map<String,Double> countMonthMap,
                                              String nextSearchDate){
        Double totalSum = 0d;
        for(Map<String,Object> objectMap : countResult){
            if(countMonthMap.containsKey(objectMap.get("times").toString())){
                Double num = Double.parseDouble(objectMap.get("num").toString());
                countMonthMap.put(objectMap.get("times").toString(),num);
                totalSum += num;
            }
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("orderList",countMonthMap);
        resultMap.put("totalSum",String.format("%.2f",totalSum));
        resultMap.put("nextSearch",nextSearchDate);
        return resultMap;
    }

    public Map<String,Object> getBussinessDayOrder(Integer businessId,
                                                   String searchDay,Integer pageNum,
                                                   Integer pageSize){
        if(pageNum < 0){
            pageNum = 1;
        }
        Pageable pageable = PageRequest.of(pageNum - 1 ,pageSize, Sort.Direction.DESC,"new_time");
        Integer startTime = (int)(DateTimeUtils.converStrToTimestamp(String.format("%s 00:00:00",searchDay)).getTime() / 1000);
        Integer endTime = (int)(DateTimeUtils.converStrToTimestamp(String.format("%s 23:59:59",searchDay)).getTime() / 1000);
        List<Map<String, Object>> countResult = bmsDxOrderDao.findDayOrder(startTime,endTime,businessId,pageable);
        Double totalSum = 0d;

        for(Map<String,Object> objectMap : countResult){
            totalSum += Double.parseDouble(objectMap.get("total_consum").toString());
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("orderList",countResult);
        resultMap.put("totalSum",String.format("%.2f",totalSum));
        resultMap.put("searchDay",searchDay);
        return ResultMapHelper.success(resultMap,"获取成功！");
    }


    public Map<String, Object> getMyOrder(String userIdentify,Integer pageNum,Integer pageSize,
                                          Integer status,Map<String,Object> searchBody) {
        RequestHeaderData requestHeaderData = new RequestHeaderData();
        Integer client = requestHeaderData.getInteger("client");
        List<BmsDxOrderStatus> bmsDxOrderStatuses = new ArrayList<>();
        Map<String,Object> userData = new HashMap<>();
        final int ALL = 1;
        final int NO_PAY = 2;
        final int CAN_USE = 3;
        final int ELSE_USER = 4;
        final int WAIT_GET = 6;
        Integer userId = Integer.parseInt(userIdentify);
        //查询待付款和可使用订单数量
        Map<String,Object> conditionMap = new HashMap<>();
        //不是小程序，排除砍价团购
        Set<Integer> orderTypes = new HashSet<>(Arrays.asList(
                new Integer[]{Constants.ONLINE_ORDER_TYPE,Constants.COUPONS_ORDER_TYPE,
                        Constants.GROUP_BUY_ORDER_TYPE,Constants.LOCAL_LIFE_ORDER_TYPE,
                        Constants.PLATFORM_ORDER_TYPE,
                        Constants.FX_ORDER_TYPE}));
        //小程序（包含砍价订单）
        Set<Integer> smallAppOrderTypes = new HashSet<>(Arrays.asList(
                new Integer[]{Constants.ONLINE_ORDER_TYPE,Constants.COUPONS_ORDER_TYPE,
                        Constants.GROUP_BUY_ORDER_TYPE,Constants.GROUP_BUY_BARGAIN_ORDER_TYPE,
                        Constants.OTA_ORDER_TYPE,
                        Constants.LOCAL_LIFE_ORDER_TYPE,Constants.PLATFORM_ORDER_TYPE,
                        Constants.FX_ORDER_TYPE}));
        conditionMap.put("orderType_IN",orderTypes);
        if(client == Constants.SMALL_PROGRAM){
            conditionMap.put("orderType_IN",smallAppOrderTypes);
        }
        Map<Integer,Integer> countNumMap = bmsDxOrderStatusService.countNoPayAndUse((Set<Integer>) conditionMap.get("orderType_IN"),userId);
        userData.put("noPayNum",countNumMap.get(Constants.NO_PAY));
        userData.put("canUse",countNumMap.get(Constants.ALREADY_USE));
        userData.put("waitGet",countNumMap.get(Constants.WAIT_GET));
        //查询订单列表
        conditionMap.put("userId",userId);
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        Map<String,Object> additionalMap = new HashMap<>();
        Pageable pageable = BmsCommonService.getPageable(pageNum ,pageSize, Sort.Direction.DESC,"newTime");
        //假如有筛选的情况
        if(searchBody != null && searchBody.size() > 0){
            //先搜索出订单id
            if(searchBody.containsKey("businessName") && StringUtils.checkNullAndEmpty(searchBody.get("businessName"))){
                /*Set<Integer> businessIds = new HashSet<>();
                List<Map<String,Object>> restMap = bmsBusinessService.getBaseDao().findByVendorNameLikeAndIsDeleteAndIsUnload(
                        searchBody.get("businessName").toString(),Constants.COMMON_FLAG_FALSE_INT,Constants.COMMON_FLAG_FALSE_INT);
                if(!(restMap.size() > 0)){
                    return ResultMapHelper.success(bmsDxOrderStatuses,userData,"获取成功");
                }
                for(Map<String,Object> objectMap : restMap){
                    businessIds.add(Integer.parseInt(objectMap.get("id").toString()));
                }
                conditionMap.put("businessId_IN",businessIds);*/
                conditionMap.put("vendorName_LIKE",searchBody.get("businessName").toString());
            }
        }
        if(status == ALL){
            //查询订单状态表的全部订单
            additionalMap.put("orderId_GB",Constants.COMMON_FLAG_FALSE);
        }else if(status == NO_PAY) {
            conditionMap.put("status", Constants.NO_PAY);
        }else if (status == CAN_USE) {
            conditionMap.put("status", Constants.ALREADY_USE);
            Set<Integer> canUserOrderTypes = new HashSet<>(Arrays.asList(
                    new Integer[]{Constants.GROUP_BUY_ORDER_TYPE,Constants.FX_ORDER_TYPE}));
            if(client == Constants.SMALL_PROGRAM){
                canUserOrderTypes.add(Constants.GROUP_BUY_BARGAIN_ORDER_TYPE);
            }
            conditionMap.put("orderType_IN",canUserOrderTypes);
        } else if (status == ELSE_USER) {
            Set<Integer> statuses = new HashSet<>();
            statuses.add(Constants.REFUND_ING);
            statuses.add(Constants.REFUND_COMPLETE);
            statuses.add(Constants.ALREADY_CANCEL);
            conditionMap.put("status_IN",statuses);
            //additionalMap.put("orderId_GB",Constants.COMMON_FLAG_FALSE);
        }else if (status == WAIT_GET) {
            conditionMap.put("status", Constants.WAIT_GET);
        }else{
            return ResultMapHelper.result(ResultCode.CODE_ORDER_TYPE_ERROR,ResultMsg.CODE_ORDER_TYPE_ERROR);
        }
        //long start = System.currentTimeMillis();
        bmsDxOrderStatuses.addAll(bmsDxOrderStatusService.getBaseDao().findAll(new SpecificationUtils(conditionMap,additionalMap), pageable).getContent());
        //long end = System.currentTimeMillis();
        //log.info("线程id{}，bmsDxOrderStatusService 耗时{}ms",threadId,end - start);
        //获取真正的订单
        //start = System.currentTimeMillis();
        getTrueOrderList(bmsDxOrderStatuses);
        //end = System.currentTimeMillis();
        //log.info("线程id{}，getTrueOrderList 耗时{}ms",threadId,end - start);
        //System.out.println(druidDataSource);
        //因技术限制，暂时采用该种做法
        /*if(status != ELSE_USER) {
            bmsDxOrders.addAll(bmsDxOrderDao.findAll(new SpecificationUtils(conditionMap), pageable).getContent());
        }*/
        //查询所有订单的总数
        userData.put("count",getUserOrderSize(userId,conditionMap));
        userData.put("serverTime",System.currentTimeMillis());


        //处理图片
        bmsDxOrderStatuses.forEach(v->{
            if(v.getBmsDxOrder() != null){
                imgPrefixService.pushSpliceField(v.getBmsDxOrder().getBmsBusiness(),"logoUrl");
            }
        });
        List<GetMyOrderRpVo> getMyOrderRpVos = BeanUtils.copyList(bmsDxOrderStatuses,GetMyOrderRpVo.class);
        return ResultMapHelper.success(getMyOrderRpVos,userData,"获取成功");
    }

    private Integer getUserOrderSize(Integer userId,Map<String,Object> paramsMap) {
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("userId",userId);
        conditionMap.putAll(paramsMap);
        Map<String,Object> additionalMap = new LinkedHashMap<>();
        additionalMap.put("orderId_GB",Constants.COMMON_FLAG_FALSE);
        int count = (int)bmsDxOrderStatusService.getBaseDao().count(new SpecificationUtils(conditionMap,additionalMap));
        return count;
    }

    public void getTrueOrderList(List<BmsDxOrderStatus> bmsDxOrderStatuses){
        if(bmsDxOrderStatuses != null && bmsDxOrderStatuses.size() > 0){
            Set<Integer> orderIds = new HashSet<>();
            for(BmsDxOrderStatus bmsDxOrderStatus : bmsDxOrderStatuses){
                orderIds.add(bmsDxOrderStatus.getOrderId());
            }
            if(orderIds.size() > 0){
                Map<String,Object> conditionMap = new HashMap<>();
                conditionMap.put("id_IN",orderIds);
                conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
                List<BmsDxOrder> bmsDxOrders = bmsDxOrderDao.findAll(new SpecificationUtils(conditionMap));
                //设置订单商家
                setOrderBusiness(bmsDxOrders);
                //设置订单消费用户名称
                setOrderUserName(bmsDxOrders);
                //设置团购订单
                setGroupBuyOrder(bmsDxOrders);
                //设置买单订单
                setPayForOrder(bmsDxOrders);
                //设置砍价订单
                setBargainOrder(bmsDxOrders);
                //设置满减券
                setFullCoupon(bmsDxOrders);
                //设置本地生活订单
                setLocalLife(bmsDxOrders);
                //设置口罩订单
                setMaskOrder(bmsDxOrders);
                //设置ota订单
                setOtaOrder(bmsDxOrders);
                //设置分销订单
                setDistOrder(bmsDxOrders);
                Map<Integer,BmsDxOrder> bmsDxOrderMap = getOrderMap(bmsDxOrders);
                for(BmsDxOrderStatus bmsDxOrderStatus : bmsDxOrderStatuses){
                    if(bmsDxOrderMap.containsKey(bmsDxOrderStatus.getOrderId())){
                        bmsDxOrderStatus.setBmsDxOrder(bmsDxOrderMap.get(bmsDxOrderStatus.getOrderId()));
                    }
                }
            }
        }
    }

    private void setDistOrder(List<BmsDxOrder> bmsDxOrders) {
        if(bmsDxOrders != null && bmsDxOrders.size() > 0){
            Set<Integer> orderIds = new HashSet<>();
            List<BmsDxGroupBuy> bmsDxGroupBuys = new ArrayList<>();
            for(BmsDxOrder bmsDxOrder : bmsDxOrders){
                if(bmsDxOrder.getOrderType() == Constants.FX_ORDER_TYPE){
                    bmsDxGroupBuys.add(bmsDxOrder.getBmsDxGroupBuy());
                    orderIds.add(bmsDxOrder.getId());
                }
            }
            if(bmsDxGroupBuys.size() > 0){
                bmsDxGroupBuyService.postHandleGroupContent(bmsDxGroupBuys,true);
            }
            for(BmsDxOrder bmsDxOrder : bmsDxOrders){
                if(bmsDxOrder.getOrderType() == Constants.FX_ORDER_TYPE){
                   if(bmsDxOrder.getBmsDxGroupBuy() != null){
                       //减少接口所产生的流量
                       bmsDxOrder.getBmsDxGroupBuy().setTextContent(null);
                       bmsDxOrder.getBmsDxGroupBuy().setGroupContent(null);
                   }
                }
            }
            if(orderIds.size() > 0){
                Map<Integer,List<BmsDxGroupBuyUse>> groupBuyUseMap = bmsDxGroupBuyUseService.getGroupByCode(orderIds);
                for(BmsDxOrder bmsDxOrder : bmsDxOrders){
                    if(groupBuyUseMap.containsKey(bmsDxOrder.getId())){
                        bmsDxOrder.setBmsDxGroupBuyUse(groupBuyUseMap.get(bmsDxOrder.getId()));
                    }
                }
            }
        }

    }

    private void setOtaOrder(List<BmsDxOrder> bmsDxOrders) {
        if(bmsDxOrders != null && bmsDxOrders.size() > 0){
            for(BmsDxOrder bmsDxOrder : bmsDxOrders){
                if(bmsDxOrder.getOrderType() == Constants.OTA_ORDER_TYPE){
                    if(bmsDxOrder.getBmsBusiness() == null){
                        bmsDxOrder.setBmsBusiness(new BmsBusiness());
                    }
                    bmsDxOrder.getBmsBusiness().setVendorName("OTA全球上网卡");
                    if(bmsDxOrder.getGoodInfos() == null){
                        bmsDxOrder.setGoodInfos(new BmsDxOrder.GoodDto());
                    }
                    String shopList = bmsDxOrder.getShopList();
                    JSONArray jsonArray = JSON.parseArray(shopList);
                    if(jsonArray.size() > 0){
                        bmsDxOrder.getGoodInfos().setGoodName(jsonArray.getJSONObject(0).getString("name"));
                        bmsDxOrder.getGoodInfos().setBusinessHeadImg("");
                        if(jsonArray.getJSONObject(0).containsKey(" previewImg")){
                            bmsDxOrder.getGoodInfos().setBusinessHeadImg(jsonArray.getJSONObject(0).getString(" previewImg"));
                        }
                    }
                }
            }
        }
    }

    private void setMaskOrder(List<BmsDxOrder> bmsDxOrders) {
        if(bmsDxOrders != null && bmsDxOrders.size() > 0){
            Set<Integer> platformIds = bmsDxOrders.stream().map(BmsDxOrder::getPlatformGoodId).collect(Collectors.toSet());
            Map<Integer,BmsPlatformGood> bmsPlatformGoodMap = bmsPlatformGoodService.findByIdIn(platformIds);
            for(BmsDxOrder bmsDxOrder : bmsDxOrders){
                if(bmsDxOrder.getOrderType() == Constants.PLATFORM_ORDER_TYPE){
                    BmsDxOrder.PlatformGoodVo platformGoodVo = new BmsDxOrder.PlatformGoodVo();
                    platformGoodVo.setActualConsum(bmsDxOrder.getActualConsum());
                    platformGoodVo.setBusinessImg(bmsDxOrder.getBmsBusiness().getLogoUrl());
                    platformGoodVo.setPlatformBuyNum(bmsDxOrder.getPlatformBuyNum());
                    if(bmsPlatformGoodMap.containsKey(bmsDxOrder.getPlatformGoodId())){
                        platformGoodVo.setGoodName(bmsPlatformGoodMap.get(bmsDxOrder.getPlatformGoodId()).getGoodName());
                    }
                    bmsDxOrder.setPlatformOrderVo(platformGoodVo);
                }
            }
        }
    }

    private void setBargainOrder(List<BmsDxOrder> bmsDxOrders) {
        if(bmsDxOrders != null && bmsDxOrders.size() > 0){
            Set<Integer> bargainId = bmsDxOrders.stream().filter(b -> Constants.GROUP_BUY_BARGAIN_ORDER_TYPE == b.getOrderType()).map(BmsDxOrder::getBargainId).collect(Collectors.toSet());
            if(bargainId.size() > 0){
                Map<Integer,BmsUserBargain> bmsUserBargains = bmsUserBargainService.getBargainByIdInMap(bargainId);
                for(BmsDxOrder bmsDxOrder : bmsDxOrders){
                    if(bmsUserBargains.containsKey(bmsDxOrder.getBargainId())) {
                        if (bmsDxOrder.getOrderType() == Constants.GROUP_BUY_BARGAIN_ORDER_TYPE) {
                            BmsDxOrder.BmsUserBargainDto bmsUserBargain = new BmsDxOrder.BmsUserBargainDto();
                            BeanUtils.copyProperties(bmsUserBargains.get(bmsDxOrder.getBargainId()),bmsUserBargain);
                            bmsDxOrder.setBmsUserBargain(bmsUserBargain);
                        }
                    }
                }
            }
        }
    }

    public void setFullCoupon(List<BmsDxOrder> bmsDxOrders) {
        if(bmsDxOrders != null && bmsDxOrders.size() > 0){
            Set<Integer> userReceFullIds = new HashSet<>();
            for(BmsDxOrder bmsDxOrder : bmsDxOrders){
                if(bmsDxOrder.getFullCouponId()!= null){
                    userReceFullIds.add(bmsDxOrder.getFullCouponId());
                }
            }
            if(userReceFullIds.size() > 0){
                Map<Integer,BmsUserReceCoupon> bmsUserReceCouponMap = bmsUserReceCouponService.getUserFullCouponMap(userReceFullIds);
                for(BmsDxOrder bmsDxOrder : bmsDxOrders){
                    if(bmsDxOrder.getFullCouponId() != null) {
                        if (bmsUserReceCouponMap.containsKey(bmsDxOrder.getFullCouponId())) {
                            BmsUserReceCoupon bmsUserReceCoupon = bmsUserReceCouponMap.get(bmsDxOrder.getFullCouponId());
                            bmsDxOrder.setBmsUserReceCoupon(bmsUserReceCoupon);
                            BmsDxOrder.BmsUserReceCouponVo bmsUserReceCouponVo = new BmsDxOrder.BmsUserReceCouponVo();
                            bmsDxOrder.setReceCoupon(bmsUserReceCouponVo);
                            bmsUserReceCouponVo.setCouponType(bmsUserReceCoupon.getType());
                            if(bmsUserReceCoupon.getBmsFullCoupon() != null){
                                bmsUserReceCouponVo.setCouponMoney(Double.parseDouble(bmsUserReceCoupon.getBmsFullCoupon().getFullRule().split("_")[1]));
                            }else if(bmsUserReceCoupon.getBmsBusinessCoupon() != null){
                                BmsBusinessCoupon bmsBusinessCoupon = bmsUserReceCoupon.getBmsBusinessCoupon();
                                bmsBusinessCoupon.setCouponContentDict(JSON.parseObject(bmsBusinessCoupon.getCouponContent()));
                                bmsUserReceCouponVo.setCouponMoney(Double.parseDouble(bmsBusinessCoupon.getCouponContentDict().get("amount").toString()));
                            }
                        }
                    }
                }
            }
        }
    }

    public Map<Integer,BmsDxOrder> getOrderMap(List<BmsDxOrder> bmsDxOrders){
        Map<Integer,BmsDxOrder> bmsDxOrderMap = new HashMap<>();
        if(bmsDxOrders != null && bmsDxOrders.size() > 0){
            for(BmsDxOrder bmsDxOrder : bmsDxOrders){
                bmsDxOrderMap.put(bmsDxOrder.getId(),bmsDxOrder);
            }
        }
        return bmsDxOrderMap;
    }

    private void setGroupBuyOrder(List<BmsDxOrder> bmsDxOrders) {
        if(bmsDxOrders != null && bmsDxOrders.size() > 0){
            List<BmsDxGroupBuy> bmsDxGroupBuys = new ArrayList<>();
            Set<Integer> orderIds = new HashSet<>();
            for(BmsDxOrder bmsDxOrder : bmsDxOrders){
                if(bmsDxOrder.getOrderType() == Constants.GROUP_BUY_ORDER_TYPE
                        || bmsDxOrder.getOrderType() == Constants.GROUP_BUY_BARGAIN_ORDER_TYPE){
                    bmsDxGroupBuys.add(bmsDxOrder.getBmsDxGroupBuy());
                    orderIds.add(bmsDxOrder.getId());
                }
            }
            if(bmsDxGroupBuys.size() > 0){
                bmsDxGroupBuyService.postHandleGroupContent(bmsDxGroupBuys,true);
            }

            if(orderIds.size() > 0){
                Map<Integer,List<BmsDxGroupBuyUse>> groupBuyUseMap = bmsDxGroupBuyUseService.getGroupByCode(orderIds);
                for(BmsDxOrder bmsDxOrder : bmsDxOrders){
                    if(groupBuyUseMap.containsKey(bmsDxOrder.getId())){
                        bmsDxOrder.setBmsDxGroupBuyUse(groupBuyUseMap.get(bmsDxOrder.getId()));
                    }
                }
            }
        }
    }

    private void setLocalLife(List<BmsDxOrder> bmsDxOrders) {
        if(bmsDxOrders != null && bmsDxOrders.size() > 0){
            List<BmsDxGroupBuy> bmsDxGroupBuys = new ArrayList<>();
            Set<Integer> lifeIds = new HashSet<>();
            Set<Integer> goodIds = new HashSet<>();
            for(BmsDxOrder bmsDxOrder : bmsDxOrders){
                if(bmsDxOrder.getOrderType() == Constants.LOCAL_LIFE_ORDER_TYPE){
                    String shopList = bmsDxOrder.getShopList();
                    if(shopList!=null){
                        List<BmsLocalLifeGoodsVo> bmsLocalLifeGoodsVos = JSONArray.parseArray(shopList, BmsLocalLifeGoodsVo.class);
                        if(bmsLocalLifeGoodsVos.size() > 0){
                            BmsLocalLifeGoodsVo bmsLocalLifeGoodsVo = bmsLocalLifeGoodsVos.get(0);
                            goodIds.add(bmsLocalLifeGoodsVo.getGoodId());
                        }
                    }
                    if(bmsDxOrder.getLifeId()!=null){
                        lifeIds.add(bmsDxOrder.getLifeId());
                    }
                }
            }
            Map<Integer,BmsLocalLifeGoods> bmsLocalLifeGoodsMap = new HashMap<>();
            Map<Integer,BmsLocalLife> bmsLocalLifeMap = new HashMap<>();
            if(goodIds.size() > 0){
                bmsLocalLifeGoodsMap = bmsLocalLifeGoodsService.getBmsLocalLifeGoodMapNotDel(goodIds);
                bmsLocalLifeMap = bmsLocalLifeService.getBmsLocalLifeMap(lifeIds);
            }
            for(BmsDxOrder bmsDxOrder : bmsDxOrders){
                String goodsName = "";
                Integer num = 0;
                BmsDxOrder.GoodDto goodDto = new BmsDxOrder.GoodDto();
                if(bmsDxOrder.getOrderType() == Constants.LOCAL_LIFE_ORDER_TYPE){
                    if(bmsDxOrder.getLifeId()!=null){
                        if(bmsLocalLifeMap.containsKey(bmsDxOrder.getLifeId())){
                            goodDto.setBusinessHeadImg(bmsLocalLifeMap.get(bmsDxOrder.getLifeId()).getBusinessHeadImg());
                        }
                    }
                    String shopList = bmsDxOrder.getShopList();
                    if(shopList!=null){
                        List<BmsLocalLifeGoodsVo> bmsLocalLifeGoodsVos = JSONArray.parseArray(shopList, BmsLocalLifeGoodsVo.class);
                        if(bmsLocalLifeGoodsVos.size()>0){
                            BmsLocalLifeGoodsVo bmsLocalLifeGoodsVo = bmsLocalLifeGoodsVos.get(0);
                            if(bmsLocalLifeGoodsMap.containsKey(bmsLocalLifeGoodsVo.getGoodId())) {
                                goodDto.setProductImg(bmsLocalLifeGoodsMap.get(bmsLocalLifeGoodsVo.getGoodId()).getGoodsImg());
                                goodsName += bmsLocalLifeGoodsMap.get(bmsLocalLifeGoodsVo.getGoodId()).getGoodsName();
                            }
                        }
                        for(BmsLocalLifeGoodsVo vo: bmsLocalLifeGoodsVos){
                            num += vo.getNum();
                        }
                        goodDto.setNum(num);
                        if(num==1){
                            goodDto.setGoodName(goodsName);
                        }else if(num>1){
                            goodDto.setGoodName(goodsName+" 等商品");
                        }
                    }
                }
                bmsDxOrder.setGoodInfos(goodDto);
            }
        }
    }

    public void setOrderBusiness(List<BmsDxOrder> bmsDxOrders) {
        if(bmsDxOrders != null && bmsDxOrders.size() > 0){
            Set<Integer> businessIds = new HashSet<>();
            for(BmsDxOrder bmsDxOrder : bmsDxOrders){
                //设置用户
                businessIds.add(bmsDxOrder.getBmsBusinessId());
            }
            if(businessIds.size() > 0){
                Map<Integer, BmsBusiness> bmsBusinessMap = bmsBusinessService.findBusinessByIdsIgnoreSetBuyCoupon(businessIds);
                for(BmsDxOrder bmsDxOrder : bmsDxOrders){
                    //设置用户
                    if(bmsBusinessMap.containsKey(bmsDxOrder.getBmsBusinessId())){
                        bmsDxOrder.setBmsBusiness(bmsBusinessMap.get(bmsDxOrder.getBmsBusinessId()));
                    }
                }
            }
        }
    }

    public void setOrderUserName(List<BmsDxOrder> bmsDxOrders) {
        if(bmsDxOrders != null && bmsDxOrders.size() > 0){
            Set<Integer> userIds = bmsDxOrders.stream().map(BmsDxOrder::getBmsUserId).collect(Collectors.toSet());
            Map<Integer,BmsUser> bmsUserMap = bmsUserService.getUserByIds(userIds);
            for(BmsDxOrder bmsDxOrder : bmsDxOrders){
                if(bmsUserMap.containsKey(bmsDxOrder.getBmsUserId())){
                    BmsUser bmsUser = bmsUserMap.get(bmsDxOrder.getBmsUserId());
                    if(bmsUser != null){
                        bmsDxOrder.setLoginName(bmsUser.getLoginName());
                        if(StringUtils.isBlank(bmsUser.getLoginName())){
                            BmsUser cacheUser = TokenManager.getUser(bmsUser.getId());
                            if(cacheUser.getSystemUser() != null && StringUtils.isNotBlank(cacheUser.getLoginName())) {
                                bmsDxOrder.setLoginName(cacheUser.getSystemUser().getLoginName());
                            }
                        }
                    }
                }
            }
        }
    }

    public Map<String, Object> showOrderDetail(Integer orderId) {
        Optional<BmsDxOrder> bmsDxOrderOptional = bmsDxOrderDao.findById(orderId);
        if(!bmsDxOrderOptional.isPresent()){
            return ResultMapHelper.failure("该订单不存在！");
        }
        BmsDxOrder bmsDxOrder = bmsDxOrderOptional.get();
        //设置用户
        Integer userId = bmsDxOrder.getBmsUserId();
        Optional<BmsUser> bmsUser = bmsUserService.getBaseDao().findById(userId);
        if(bmsUser.isPresent()){
            bmsDxOrder.setLoginName(bmsUser.get().getLoginName());
        }
        //设置优惠买单时间
        if(bmsDxOrder.getBmsCouponId() != null){
            List<BmsDxCoupon> bmsDxCoupons = new LinkedList<>();
            bmsDxCoupons.add(bmsDxOrder.getBmsDxCoupon());
            bmsDxCouponService.setIsUse(bmsDxCoupons);
            bmsDxCouponService.setUserWeek(bmsDxCoupons);
        }
        return ResultMapHelper.success(bmsDxOrder,"获取成功");

    }

    public Integer getBusinessConsumerUsersNum(Integer businessId,Integer status) {
        return bmsDxOrderDao.countBusinessConsumerUsersNum(businessId,status);
    }

    public Double countOrderTotalByType(Integer businessId,Set orderType,Integer status) {
        return bmsDxOrderDao.countBusinessOrderTotalByType(businessId,orderType,status);
    }

    public Double countOrderTotalByType(Integer businessId,Set orderType,Integer status,String startTime,String endTime) {
        Set<Integer> businessIds = new HashSet<>();
        businessIds.add(businessId);
        return bmsDxOrderDao.countBusinessOrderTotalByTypeAndPayTime(businessIds,orderType,status,
                startTime,endTime,Constants.MS_GEN_DATEFORMAT);
    }

    public Double countOrderTotalByType(Set businessIds,Set orderType,Integer status,String startTime,String endTime) {
        return bmsDxOrderDao.countBusinessOrderTotalByTypeAndPayTime(businessIds,orderType,status,
                startTime,endTime,Constants.MS_GEN_DATEFORMAT);
    }

    public Double countOrderTotalByType(Integer businessId,Integer orderType,Integer status) {
        Set orderTypes = new HashSet();
        orderTypes.add(orderType);
        return bmsDxOrderDao.countBusinessOrderTotalByType(businessId,orderTypes,status);
    }

    public Integer countBusinessOrderNum(Integer businessId,Set orderTypes,Integer status,String startTime,String endTime){
        return bmsDxOrderDao.countBusinessOrderNum(businessId,orderTypes,status,startTime,endTime,Constants.MS_GEN_DATEFORMAT);
    }

    public void setPayForOrder(List<BmsDxOrder> bmsDxOrders) {
        if(bmsDxOrders != null && bmsDxOrders.size() > 0){
            List<BmsDxCoupon> bmsDxCoupons = new LinkedList<>();
            for(BmsDxOrder bmsDxOrder : bmsDxOrders){
                if(bmsDxOrder.getBmsDxCoupon() != null){
                    bmsDxCoupons.add(bmsDxOrder.getBmsDxCoupon());
                }
            }
            bmsDxCouponService.setUserWeek(bmsDxCoupons);
        }
    }

    public void setGroupOrder(List<BmsDxGroupBuyUse> bmsDxGroupBuyUses){
        if(bmsDxGroupBuyUses != null && bmsDxGroupBuyUses.size() > 0){
            Set<Integer> orderIds = new HashSet<>();
            Set<Integer> assistantIds = new HashSet<>();
            for(BmsDxGroupBuyUse bmsDxGroupBuyUse : bmsDxGroupBuyUses){
                orderIds.add(bmsDxGroupBuyUse.getOrderId());
                if(bmsDxGroupBuyUse.getUseManRole() != null && bmsDxGroupBuyUse.getUseManRole() == Constants.ASSISTANT_ROLE_ID){
                    assistantIds.add(bmsDxGroupBuyUse.getUseManId());
                }
            }
            //查询店员数据
            Map<Integer,BmsUserBusiness> bmsUserBusinessMap = bmsUserBusinessService.getAssistantMap(assistantIds);
            //查询使用团购券张数
            Map<Integer,Map<Long,Map<String,Object>>> useNumMap = getGroupBuyUserCodition(orderIds);
            if(orderIds.size() > 0){
                Map<String,Object> conditionMap = new HashMap<>();
                conditionMap.put("id_IN",orderIds);
                List<BmsDxOrder> bmsDxOrders = bmsDxOrderDao.findAll(new SpecificationUtils(conditionMap));
                setOrderBusiness(bmsDxOrders);
                setOrderUserName(bmsDxOrders);
                //设置满减券
                setFullCoupon(bmsDxOrders);
                Map<Integer,BmsDxOrder> orderMap = getOrderMap(bmsDxOrders);
                for(BmsDxGroupBuyUse bmsDxGroupBuyUse : bmsDxGroupBuyUses){
                    //设置订单
                    if(orderMap.containsKey(bmsDxGroupBuyUse.getOrderId())){
                        bmsDxGroupBuyUse.setBmsDxOrder(orderMap.get(bmsDxGroupBuyUse.getOrderId()));
                        if(bmsDxGroupBuyUse.getBmsDxOrder().getBmsDxGroupBuy() != null){
                            bmsDxGroupBuyService.postHandleGroupBuy(bmsDxGroupBuyUse.getBmsDxOrder().getBmsDxGroupBuy(),true);
                            //bmsDxGroupBuyUse.getBmsDxOrder().getBmsDxGroupBuy().setTextContent(null);
                            bmsDxGroupBuyUse.getBmsDxOrder().getBmsDxGroupBuy().setGroupContent(null);
                        }
                    }
                    //设置张数
                    if(useNumMap.containsKey(bmsDxGroupBuyUse.getOrderId())){
                        Map<Long,Map<String,Object>> useCondtion = useNumMap.get(bmsDxGroupBuyUse.getOrderId());
                        if(useCondtion.containsKey(bmsDxGroupBuyUse.getUseTime().getTime())){
                            Map<String,Object> use = useCondtion.get(bmsDxGroupBuyUse.getUseTime().getTime());
                            bmsDxGroupBuyUse.setAlreadyCancelNum(Integer.parseInt(use.get("num").toString()));
                        }
                    }
                    //设置核销人员
                    if(StringUtils.isBlank(bmsDxGroupBuyUse.getNickName())) {
                        if (bmsDxGroupBuyUse.getUseManRole() != null && bmsDxGroupBuyUse.getUseManRole() == Constants.ASSISTANT_ROLE_ID) {
                            if (bmsUserBusinessMap.containsKey(bmsDxGroupBuyUse.getUseManId())) {
                                bmsDxGroupBuyUse.setNickName(String.format("店员-%s", bmsUserBusinessMap.get(bmsDxGroupBuyUse.getUseManId()).getNameInStore()));
                            }
                        } else {
                            bmsDxGroupBuyUse.setNickName("管理员");
                        }
                    }
                }
            }
        }
    }

    public Map<Integer,Map<Long,Map<String,Object>>> getGroupBuyUserCodition(Set orderIds){
        List<Map<String,Object>> res = bmsDxGroupBuyUseService.getGroupBuyNumMap(orderIds);
        Map<Integer,Map<Long,Map<String,Object>>> useNumMap = new HashMap<>();
        if(res != null && res.size() > 0){
            for(Map<String,Object> objectMap : res){
                Integer orderId = Integer.parseInt(objectMap.get("order_id").toString());
                if(!useNumMap.containsKey(orderId)){
                    useNumMap.put(orderId,new HashMap<>());
                }
                Timestamp timestamp = (Timestamp) objectMap.get("use_time");
                useNumMap.get(orderId).put(timestamp.getTime(),objectMap);
            }
        }
        return useNumMap;
    }

    /**
     * @Description 用户删除订单
     * @Param Map
     * @return Map
     * @Author: cfx
     * @Date: 2019/8/2
     */
    @Transactional
    public Map<String, Object> userDeleteOrder(Map<String, Object> paramsMap) {
        Integer orderId = Integer.parseInt(paramsMap.get("orderId").toString());
        Integer userId = Integer.parseInt(paramsMap.get("userIdentify").toString());
        Map<String,Object> checkMap = checkOrderIsTrue(userId,orderId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        BmsDxOrder bmsDxOrder = (BmsDxOrder) checkMap.get("data");
        //同时删除订单状态表的记录
        List<BmsDxOrderStatus> bmsDxOrderStatuses = bmsDxOrderStatusService.getBaseDao().findByOrderId(bmsDxOrder.getId());
        if(bmsDxOrderStatuses != null && bmsDxOrderStatuses.size() > 0){
            for(BmsDxOrderStatus bmsDxOrderStatus : bmsDxOrderStatuses){
                if(bmsDxOrderStatus.getStatus() == Constants.ALREADY_USE){
                    return ResultMapHelper.result(ResultCode.CODE_ORDER_HAVE_USE,ResultMsg.MSG_ORDER_HAVE_USE);
                }
            }
        }
        bmsDxOrder.setIsDelete(Constants.COMMON_FLAG_TRUE_INT);
        bmsDxOrderDao.save(bmsDxOrder);
        if(bmsDxOrderStatuses != null && bmsDxOrderStatuses.size() > 0){
            for(BmsDxOrderStatus bmsDxOrderStatus : bmsDxOrderStatuses){
                bmsDxOrderStatus.setIsDelete(Constants.COMMON_FLAG_TRUE_INT);
            }
        }
        bmsDxOrderStatusService.getBaseDao().saveAll(bmsDxOrderStatuses);
        return ResultMapHelper.success(bmsDxOrder,ResultMsg.DELETE_SUCCESS);
    }

    /**
     * @Description 用户取消订单
     * @Param Map
     * @return Map
     * @Author: cfx
     * @Date: 2019/8/2
     */
    public synchronized Map<String, Object> userCancelOrder(Map<String, Object> paramsMap) {
        Integer userId = Integer.parseInt(paramsMap.get("userIdentify").toString());
        Integer orderId = Integer.parseInt(paramsMap.get("orderId").toString());
        Map<String,Object> checkMap = checkOrderIsTrue(userId,orderId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        BmsDxOrder bmsDxOrder = (BmsDxOrder) checkMap.get("data");
        //获取订单状态
        userCancelOrder(bmsDxOrder);
        return ResultMapHelper.success(bmsDxOrder,ResultMsg.CANCEL_SUCCESS);
    }

    /**
     * @Description 用户取消订单逻辑
     * @Param BmsDxOrder
     * @Author: cfx
     * @Date: 2019/9/22
     */
    public void userCancelOrder(BmsDxOrder bmsDxOrder){
        //获取订单状态
        BmsDxOrderStatus bmsDxOrderStatus = bmsDxOrderStatusService.getBaseDao().findByOrderIdAndStatus(bmsDxOrder.getId(),Constants.NO_PAY);
        if(bmsDxOrderStatus != null){
            bmsDxOrderStatus.setStatus(Constants.ALREADY_CANCEL);
            bmsDxOrderStatusService.getBaseDao().save(bmsDxOrderStatus);
            if(bmsDxOrderStatus.getOrderType() == Constants.GROUP_BUY_ORDER_TYPE){
                BmsDxGroupBuy bmsDxGroupBuy = bmsDxOrder.getBmsDxGroupBuy();
                if(bmsDxGroupBuy.getSellInventory() != null) {
                    bmsDxGroupBuy.setSellInventory(bmsDxGroupBuy.getSellInventory() + bmsDxOrder.getGroupBuyNum());
                    bmsDxGroupBuyService.getBaseDao().save(bmsDxGroupBuy);
                }
                //如果是特特乐团购
                if(bmsDxGroupBuy.getGroupType() != null && bmsDxGroupBuy.getGroupType() == Constants.GROUP_TYPE_TETE){
                    //特特乐库存回归
                    bmsThirdCodeService.stockReturn(bmsDxOrder.getId());
                }
            }else if(bmsDxOrderStatus.getOrderType() == Constants.GROUP_BUY_BARGAIN_ORDER_TYPE){
                BmsDxGroupBuy bmsDxGroupBuy = bmsDxOrder.getBmsDxGroupBuy();
                if(bmsDxGroupBuy.getSellInventory() != null) {
                    bmsDxGroupBuy.setSellInventory(bmsDxGroupBuy.getSellInventory() + bmsDxOrder.getGroupBuyNum());
                    bmsDxGroupBuyService.getBaseDao().save(bmsDxGroupBuy);
                }
            }else if(bmsDxOrderStatus.getOrderType() == Constants.PLATFORM_ORDER_TYPE){
                handlePlatformOrderCancel(bmsDxOrder);
            }
            //如果有用券
            if(bmsDxOrder.getFullCouponId() != null){
                //更新券的状态
                bmsUserReceCouponService.updateFullCouponIsUse(bmsDxOrder.getFullCouponId());
                //券回归（redis）
                bmsUserReceCouponService.removeFullCouponUseNum(bmsDxOrder.getFullCouponId());
            }
            //如果有用返现卡
            if(bmsDxOrder.getBackCardId() != null){
                //将返现的卡的钱回至返现卡
                bmsBackCardService.addMoney(bmsDxOrder.getBackCardId(),bmsDxOrder.getUseCardMoney());
            }
            //TODO 如果有用分销余额抵扣
            if(bmsDxOrder.getUseFxMoney() != null){
                CancelOrderDto cancelOrderDto = new CancelOrderDto();
                BmsDxGroupBuy bmsDxGroupBuy = bmsDxOrder.getBmsDxGroupBuy();
                cancelOrderDto.setOrderId(bmsDxOrder.getId());
                cancelOrderDto.setUserId(bmsDxOrder.getBmsUserId());
                cancelOrderDto.setGroupBuyNum(bmsDxOrder.getGroupBuyNum());
                cancelOrderDto.setUseFxMoney(bmsDxOrder.getUseFxMoney());
                cancelOrderDto.setShareUserId(bmsDxOrder.getShareId());
                if(bmsDxGroupBuy!=null){
                    cancelOrderDto.setCommision(bmsDxGroupBuy.getCommision());
                    cancelOrderDto.setAcrossCommision(bmsDxGroupBuy.getAcrossCommision());
                }
                Map<String, Object> cancelOrderMap = fxCenterService.cancelOrder(cancelOrderDto);
                if(cancelOrderMap.get("status") != null && cancelOrderMap.get("status").equals("00")){
                    System.out.println(cancelOrderMap);
                }

            }
        }

    }

    private void handlePlatformOrderCancel(BmsDxOrder bmsDxOrder) {
        //库存回归
        Integer goodId = bmsDxOrder.getPlatformGoodId();
        Integer num = bmsDxOrder.getPlatformBuyNum();
        BmsPlatformGood bmsPlatformGood = bmsPlatformGoodService.findById(goodId);
        if(bmsPlatformGood != null){
            for(int count = 0;count < 100;count++){
                Integer updateRow = bmsPlatformGoodService.updateLoseGoodInventory(bmsPlatformGood.getId(),num,bmsPlatformGood.getVersion());
                if(updateRow == 1){
                    break;
                }
            }
        }
        //设置已买
        redisTemplate.opsForZSet().incrementScore(Constants.REDIS_KEY_PLATFORM_ALREADY_BUY,"user:" + bmsDxOrder.getBmsUserId(),-num);
        Double score = redisTemplate.opsForZSet().score(Constants.REDIS_KEY_PLATFORM_ALREADY_BUY,"user:" + bmsDxOrder.getBmsUserId());
        if(score < 0d){
            redisTemplate.opsForZSet().add(Constants.REDIS_KEY_PLATFORM_ALREADY_BUY,"user:" + bmsDxOrder.getBmsUserId(),0d);
        }
        //设置今天
        if(redisTemplate.hasKey(Constants.REDIS_KEY_TODAY_BUY + bmsDxOrder.getBmsUserId() + ":" + bmsDxOrder.getPlatformGoodId())) {
            redisTemplate.delete(Constants.REDIS_KEY_TODAY_BUY + bmsDxOrder.getBmsUserId() + ":" + bmsDxOrder.getPlatformGoodId());
        }
    }

    public Map<String,Object> checkOrderIsTrue(Integer userId,Integer orderId){
        BmsDxOrder bmsDxOrder = bmsDxOrderDao.findByIdAndIsDelete(orderId,Constants.COMMON_FLAG_FALSE_INT);
        if(bmsDxOrder == null){
            return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_EXIST,ResultMsg.CODE_ORDER_NO_EXIST);
        }
        if(bmsDxOrder.getBmsUserId() != userId.intValue()){
            return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_BELONG,ResultMsg.CODE_ORDER_NO_BELONG);
        }
        return ResultMapHelper.success(bmsDxOrder);
    }

    @Transactional(rollbackFor = Exception.class)
    public Map<String,Object> refundOrder(ParamsMap paramsMap) throws Exception {
        Map<String,Object> handleMap = bmsDxOrderService.userRefundOrderOrder(paramsMap);
        if(!ResultCode.CODE_NORMAL.equals(handleMap.get("status").toString())){
            return handleMap;
        }
        BmsDxOrder bmsDxOrder = (BmsDxOrder) handleMap.get("data");
        Map<String,Object> userDataMap = (Map<String, Object>) handleMap.get("userData");
        if(bmsDxOrder.getCreateWay() == null){
            bmsDxOrder.setCreateWay(Constants.ANDROID_CLIENT);
        }
        boolean isRefund = false;
        //退款金额
        Double orderRefund = Double.parseDouble(userDataMap.get("refundTotal").toString());
        if(bmsDxOrder.getPayWay() == Constants.ALI_PAY) {
            isRefund = aliPayService.refundMoney(bmsDxOrder,orderRefund,aliPayService.getAlipayClient(DateTimeUtils.converDateToInterger(bmsDxOrder.getNewTime())));
        }else if(bmsDxOrder.getPayWay() == Constants.WX_PAY){
            WxPayBean wxPayConfig = wxPayService.getApiConfigByChannel(WxPayBeanFactory.MIN_APP_CHANNEL);
            isRefund = wxPayService.refundMoney(bmsDxOrder, orderRefund, wxPayConfig);
        }
        if(!isRefund){
            throw new Exception("退款失败");
        }
        List<BmsDxGroupBuyUse> groupBuyUseList = (List<BmsDxGroupBuyUse>) userDataMap.get("bmsDxGroupBuyUses");
        //存储处理时间
        Date nowTime = new Date();
        for(BmsDxGroupBuyUse bmsDxGroupBuyUse : groupBuyUseList){
            bmsDxGroupBuyUse.setAcceptTime(nowTime);
            bmsDxGroupBuyUse.setRefundTime(nowTime);
        }
        userDataMap.put("refundTime", DateTimeUtils.converDateToString(groupBuyUseList.get(0).getRefundTime(),DateTimeUtils.DATE_PATTERN_DAY_05));
        userDataMap.put("refundNum",groupBuyUseList.size());
        //保存状态和时间
        bmsDxGroupBuyUseService.getBaseDao().saveAll(groupBuyUseList);
        //发送消息
        BmsCommonService.getApplicationContext().publishEvent(new OrderEvent("orderRefund_success",bmsDxOrder,userDataMap));
        return ResultMapHelper.success(userDataMap, ResultMsg.CODE_ORDER_RUFUND_SUCCESS);
    }

    public Map<String, Object> userRefundOrderOrder(ParamsMap paramsMap){
        Date nowTime = new Date();
        Map<String,Object> userDataMap = new HashMap<>();
        Integer userId = Integer.parseInt(paramsMap.get("userIdentify").toString());
        Integer orderId = Integer.parseInt(paramsMap.get("orderId").toString());
        Map<String,Object> checkMap = checkOrderIsTrue(userId,orderId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        BmsDxOrder bmsDxOrder = (BmsDxOrder) checkMap.get("data");
        BmsDxGroupBuy bmsDxGroupBuy = bmsDxOrder.getBmsDxGroupBuy();
        if(bmsDxGroupBuy.getIsRefundAnyTime() != null) {
            if (bmsDxGroupBuy.getIsRefundAnyTime() == Constants.COMMON_FLAG_FALSE_INT) {
                return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_SUPPORT_REFUND, ResultMsg.CODE_ORDER_NO_REFUND_ANY);
            }
        }
        if(bmsDxGroupBuy.getExpireTime() != null){
            if(nowTime.getTime() >= DateTimeUtils.addDay(bmsDxGroupBuy.getExpireTime(),1).getTime()){
                if(bmsDxGroupBuy.getIsOverdueRefund() != null){
                    if(bmsDxGroupBuy.getIsOverdueRefund() == Constants.COMMON_FLAG_FALSE_INT){
                        return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_SUPPORT_REFUND, ResultMsg.CODE_ORDER_NO_REFUND_OVER);
                    }
                }
            }
        }
        List<String> groupBuyIds;
        if(paramsMap.get("groupBuyUseIds") instanceof String){
            groupBuyIds = (List<String>) JSON.parse(paramsMap.get("groupBuyUseIds").toString());
        }else {
            groupBuyIds = (List) paramsMap.get("groupBuyUseIds");
        }
        Set<Integer> groupBuyUseIds = new HashSet<>();
        for(String groupById : groupBuyIds){
            groupBuyUseIds.add(Integer.parseInt(groupById));
        }
        //查看团购券是否已经是已退款状态
        List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = bmsDxGroupBuyUseService.getBaseDao().findByIdIn(groupBuyUseIds);
        if(!(bmsDxGroupBuyUses != null && bmsDxGroupBuyUses.size() > 0)) {
            return ResultMapHelper.result(ResultCode.CODE_ORDER_GROUP_NO_EXIST, ResultMsg.CODE_ORDER_GROUP_NO_EXIST);
        }
        for(BmsDxGroupBuyUse bmsDxGroupBuyUse : bmsDxGroupBuyUses){
            if(bmsDxGroupBuyUse.getStatus() == Constants.GROUP_REFUND_COMPLETE){
                return ResultMapHelper.result(ResultCode.CODE_ORDER_GROUP_AL_REFUND,ResultMsg.CODE_ORDER_GROUP_AL_REFUND);
            }
            if(bmsDxGroupBuyUse.getStatus() == Constants.GROUP_ALREADY_USE){
                return ResultMapHelper.result(ResultCode.CODE_ORDER_GROUP_AL_USE,ResultMsg.CODE_ORDER_GROUP_AL_USE);
            }
            if(bmsDxGroupBuyUse.getOrderId() != orderId.intValue()){
                return ResultMapHelper.result(ResultCode.CODE_ORDER_GROUP_USE_NO_MATCH_ORDER,ResultMsg.CODE_ORDER_GROUP_USE_NO_MATCH_ORDER);
            }
        }

        if(bmsDxOrder.getOrderType() == Constants.ONLINE_ORDER_TYPE
                || bmsDxOrder.getOrderType() == Constants.COUPONS_ORDER_TYPE){
            return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_SUPPORT_REFUND,ResultMsg.CODE_ORDER_NO_SUPPORT_REFUND);
        }
        Double total = 0d;
        Double useBackMoney = 0d;
        for(BmsDxGroupBuyUse bmsDxGroupBuyUse : bmsDxGroupBuyUses){
            bmsDxGroupBuyUse.setStatus(Constants.GROUP_REFUND_COMPLETE);
            bmsDxGroupBuyUse.setAuditTime(nowTime);
            bmsDxGroupBuyUse.setCommitTime(nowTime);
            bmsDxGroupBuyUse.setApprovedTime(nowTime);
            total = ArithUtil.add(total,bmsDxGroupBuyUse.getGbuyActualConsum());
            if(bmsDxGroupBuyUse.getBackCacdMoney() != null){
                useBackMoney = ArithUtil.add(useBackMoney,bmsDxGroupBuyUse.getBackCacdMoney());
            }
        }
        userDataMap.put("bmsDxGroupBuyUses",bmsDxGroupBuyUses);
        //查看之前是否已经退款了
        BmsDxOrderStatus bmsDxOrderStatus = bmsDxOrderStatusService.
                getBaseDao().findByOrderIdAndStatus(orderId,Constants.REFUND_COMPLETE);
        if(bmsDxOrderStatus == null){
            bmsDxOrderStatus = new BmsDxOrderStatus();
            bmsDxOrderStatus.setOrderId(bmsDxOrder.getId());
            bmsDxOrderStatus.setOrderType(bmsDxOrder.getOrderType());
            bmsDxOrderStatus.setUserId(bmsDxOrder.getBmsUserId());
            bmsDxOrderStatus.setStatus(Constants.REFUND_COMPLETE);
            bmsDxOrderStatus.setNewTime(bmsDxOrder.getNewTime());
            bmsDxOrderStatus.setBusinessId(bmsDxOrder.getBmsBusinessId());
            bmsDxOrderStatus.setPayTime(bmsDxOrder.getPayTime());
        }
        bmsDxOrderStatusService.getBaseDao().save(bmsDxOrderStatus);
        //查看是否全额退款
        int alreadRufund = bmsDxGroupBuyUseService.getBaseDao().countOrderStatuNum(orderId,Constants.GROUP_REFUND_COMPLETE);
        if(alreadRufund == bmsDxOrder.getGroupBuyNum()) {
            bmsDxOrderStatus = bmsDxOrderStatusService.
                    getBaseDao().findByOrderIdAndStatus(orderId, Constants.ALREADY_USE);
            bmsDxOrderStatusService.getBaseDao().delete(bmsDxOrderStatus);
        }else if(alreadRufund < bmsDxOrder.getGroupBuyNum()){
            //查看没用的记录
            Map<String,Object> conditionMap = new HashMap<>();
            conditionMap.put("orderId",orderId);
            conditionMap.put("status",Constants.GROUP_ALREADY_USE);
            Integer useNum = (int)bmsDxGroupBuyUseService.getBaseDao().count(new SpecificationUtils(conditionMap));
            if((useNum + alreadRufund) == bmsDxOrder.getGroupBuyNum()){
                //代表订单完成
                bmsDxOrderStatus = bmsDxOrderStatusService.
                        getBaseDao().findByOrderIdAndStatus(orderId, Constants.ALREADY_USE);
                bmsDxOrderStatus.setStatus(Constants.PAY_COMPLETE);
                bmsDxOrderStatusService.getBaseDao().save(bmsDxOrderStatus);
            }
        }
        //将退款的张数退回至团购券
        if(bmsDxGroupBuy.getSellInventory() != null) {
            bmsDxGroupBuy.setSellInventory(bmsDxGroupBuy.getSellInventory() + bmsDxGroupBuyUses.size());
            bmsDxGroupBuyService.getBaseDao().save(bmsDxGroupBuy);
        }
        //如果是特特乐团购，库存回归
        if(bmsDxGroupBuy.getGroupType() != null && bmsDxGroupBuy.getGroupType() == Constants.GROUP_TYPE_TETE){
            Set<String> codes = bmsDxGroupBuyUses.stream().map(BmsDxGroupBuyUse::getGroupBuyCode).collect(Collectors.toSet());
            bmsThirdCodeService.stockReturn(codes,orderId);
        }
        //如果有满减券的情况调回未使用
        if(bmsDxOrder.getFullCouponId() != null){
            //是否退完
            if(alreadRufund == bmsDxOrder.getGroupBuyNum()) {
                bmsUserReceCouponService.updateFullCouponIsUse(bmsDxOrder.getFullCouponId());
                bmsUserReceCouponService.removeFullCouponUseNum(bmsDxOrder.getFullCouponId());
            }
        }
        if(bmsDxOrder.getBackCardId() != null){
            //将返现的卡的钱回至返现卡
            bmsBackCardService.addMoney(bmsDxOrder.getBackCardId(),useBackMoney);
        }
        userDataMap.put("refundTotal",total);
        userDataMap.put("groupBuyId",bmsDxGroupBuy.getId());
        return ResultMapHelper.success(bmsDxOrder,userDataMap);
    }

    public Map<String, Object> checkOrderCanPay(BmsDxOrder bmsDxOrder) {
        if(bmsDxOrder.getOrderType() == Constants.COUPONS_ORDER_TYPE){
            //优惠买单,判断是否超过购买限制
            /*BmsDxCoupon bmsDxCoupon = bmsDxOrder.getBmsDxCoupon();
            if(bmsDxCoupon.getUseNum() != Constants.COMMON_FLAG_FALSE_INT){
                //有使用次数限制，查询当前用户是否达到使用次数
                Integer num = bmsDxOrderDao.countUserUseCouponNum(bmsDxOrder.getBmsUserId(),bmsDxCoupon.getId());
                System.out.println(num);
                if(num.intValue() >= bmsDxCoupon.getUseNum()){
                    return ResultMapHelper.result(ResultCode.CODE_ORDER_ONLINEPAY_MAX,ResultMsg.CODE_ORDER_ONLINEPAY_MAX);
                }
            }*/
        }
        return ResultMapHelper.success();
    }

    public Map<String, Object> userGetNewsOrderDisplay(ParamsMap paramsMap) {
        //Integer userId = Integer.parseInt(paramsMap.get("userIdentify").toString());
        Integer orderId = Integer.parseInt(paramsMap.get("orderId").toString());
        Integer isShowVer = paramsMap.getInteger("isShowVer");
        /*BmsDxOrder bmsDxOrder = bmsDxOrderDao.findByIdAndIsDelete(orderId,Constants.COMMON_FLAG_FALSE_INT);
        if(bmsDxOrder == null){
            return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_EXIST,ResultMsg.CODE_ORDER_NO_EXIST);
        }*/
        Optional<BmsDxOrder> bmsDxOrderOptional = bmsDxOrderDao.findById(orderId);
        if(!bmsDxOrderOptional.isPresent()){
            return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_EXIST,ResultMsg.CODE_ORDER_NO_EXIST);
        }
        BmsDxOrder bmsDxOrder = bmsDxOrderOptional.get();
        List<BmsDxOrder>  bmsDxOrders = new LinkedList<>();
        bmsDxOrders.add(bmsDxOrder);
        //设置消费用户
        setOrderUserName(bmsDxOrders);
        //设置店铺名称
        setOrderBusiness(bmsDxOrders);
        //设置团购券
        setFullCoupon(bmsDxOrders);
        UserGetNewsOrderDisplayRpVo userGetNewsOrderDisplayRpVo = new UserGetNewsOrderDisplayRpVo();
        if(bmsDxOrder.getOrderType() == Constants.ONLINE_ORDER_TYPE
                || bmsDxOrder.getOrderType() == Constants.COUPONS_ORDER_TYPE){
            setPayForOrder(bmsDxOrders);
        }else if(bmsDxOrder.getOrderType() == Constants.GROUP_BUY_ORDER_TYPE
                || bmsDxOrder.getOrderType() == Constants.GROUP_BUY_BARGAIN_ORDER_TYPE
                || bmsDxOrder.getOrderType() == Constants.FX_ORDER_TYPE){
            Integer groupBuyUseId = null;
            if(paramsMap.containsKey("groupBuyUseId")
                    && StringUtils.checkNullAndEmpty(paramsMap.get("groupBuyUseId"))
                    && paramsMap.getInteger("groupBuyUseId") != Constants.COMMON_FLAG_FALSE_INT){
                groupBuyUseId = Integer.parseInt(paramsMap.get("groupBuyUseId").toString());
            }
            if(groupBuyUseId != null){
                //核销消息
                Optional<BmsDxGroupBuyUse> bmsDxGroupBuyUseOptional = bmsDxGroupBuyUseService.getBaseDao().findById(groupBuyUseId);
                if(bmsDxGroupBuyUseOptional.isPresent()){
                    BmsDxGroupBuyUse groupBuyUse = bmsDxGroupBuyUseOptional.get();
                    BeanUtils.copyProperties(groupBuyUse,userGetNewsOrderDisplayRpVo);
                    if(groupBuyUse.getOrderId().intValue() != bmsDxOrder.getId().intValue()) {
                        return ResultMapHelper.result(ResultCode.CODE_ORDER_GROUP_USE_NO_MATCH_ORDER,ResultMsg.CODE_ORDER_GROUP_USE_NO_MATCH_ORDER);
                    }
                    if(groupBuyUse.getStatus() == Constants.GROUP_REFUND_COMPLETE){
                        //找出退款流程的所有订单
                        /*Map<String,Object> conditionMap = new HashMap<>();
                        conditionMap.put("orderId",groupBuyUse.getOrderId());
                        conditionMap.put("status",Constants.GROUP_REFUND_COMPLETE);
                        conditionMap.put("commitTime",groupBuyUse.getCommitTime());
                        conditionMap.put("auditTime",groupBuyUse.getAcceptTime());
                        conditionMap.put("approvedTime",groupBuyUse.getApprovedTime());
                        conditionMap.put("acceptTime",groupBuyUse.getAcceptTime());
                        conditionMap.put("refundTime",groupBuyUse.getRefundTime());
                        List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = bmsDxGroupBuyUseService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
                        if(bmsDxGroupBuyUse != null && bmsDxGroupBuyUses.size() > 0){
                            BeanUtils.copyProperties(bmsDxGroupBuyUses.get(0),bmsDxGroupBuyUse);
                            Double refundTotal = 0d;
                            for(BmsDxGroupBuyUse bu : bmsDxGroupBuyUses){
                                refundTotal = ArithUtil.add(refundTotal,bu.getGbuyActualConsum());
                            }
                            bmsDxGroupBuyUse.setRefundMoney(refundTotal);
                        }*/
                    }else {
                        //查询该店员核销张数
                        userGetNewsOrderDisplayRpVo.setAlreadyCancelNum(getBmsDxGroupBuyUseNum(groupBuyUse,isShowVer));
                        //设置核销人员
                        if(StringUtils.isBlank(userGetNewsOrderDisplayRpVo.getNickName())) {
                            if (groupBuyUse.getUseManRole() == Constants.ASSISTANT_ROLE_ID) {
                                List<BmsUserBusiness> bmsUserBusinesses = bmsUserBusinessService.getBaseDao().findByBmsUserId(groupBuyUse.getUseManId());
                                if (bmsUserBusinesses != null && bmsUserBusinesses.size() > 0) {
                                    userGetNewsOrderDisplayRpVo.setNickName(String.format("店员-%s", bmsUserBusinesses.get(0).getNameInStore()));
                                }
                            } else {
                                userGetNewsOrderDisplayRpVo.setNickName("管理员");
                            }
                        }
                    }
                }
            }
        }
        userGetNewsOrderDisplayRpVo.setBmsDxOrder(bmsDxOrder);
        if(userGetNewsOrderDisplayRpVo.getBmsDxOrder() != null && userGetNewsOrderDisplayRpVo.getBmsDxOrder().getBmsDxGroupBuy() != null){
            BmsDxGroupBuy bmsDxGroupBuy = userGetNewsOrderDisplayRpVo.getBmsDxOrder().getBmsDxGroupBuy();
            if(StringUtils.isNotBlank(bmsDxGroupBuy.getTextContent())) {
                userGetNewsOrderDisplayRpVo.setRichText(bmsDxGroupBuy.getTextContent());
            }
            bmsDxGroupBuy.setTextContent(null);
            bmsDxGroupBuyService.postHandleGroupBuy(bmsDxGroupBuy,true);
            Integer isRealTimeAccount = userGetNewsOrderDisplayRpVo.getBmsDxOrder().getBmsDxGroupBuy().getIsRealTimeAccount();
            if(isRealTimeAccount == Constants.COMMON_FLAG_FALSE_INT){
                userGetNewsOrderDisplayRpVo.setReceivedDesc("线下结算");
            }
        }
        return ResultMapHelper.success(userGetNewsOrderDisplayRpVo,ResultMsg.MSG_GET_SUCCESS);
    }

    /**
     * @Description 获取
     * @Author: cfx
     * @Date: 2019/9/3
     */
    public Integer getBmsDxGroupBuyUseNum(BmsDxGroupBuyUse bmsDxGroupBuyUse,Integer isShowVer) {
        Map<String,Object> verMap = new HashMap<>();
        verMap.put("orderId",bmsDxGroupBuyUse.getOrderId());
        verMap.put("userId",bmsDxGroupBuyUse.getUserId());
        verMap.put("status",Constants.GROUP_ALREADY_USE);
        verMap.put("useManId",bmsDxGroupBuyUse.getUseManId());
        verMap.put("useManRole",bmsDxGroupBuyUse.getUseManRole());
        verMap.put("useWay",bmsDxGroupBuyUse.getUseWay());
        if(!(isShowVer != null && isShowVer == Constants.COMMON_FLAG_TRUE_INT)) {
            verMap.put("useTime", bmsDxGroupBuyUse.getUseTime());
        }
        List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = bmsDxGroupBuyUseService.getBaseDao().findAll(new SpecificationUtils(verMap));
        return bmsDxGroupBuyUses.size();
    }

    public Map<Integer, BmsDxOrder> getOrderMap(Set<Integer> orderIds) {
        List<BmsDxOrder> bmsDxOrders =  bmsDxOrderDao.findByIdIn(orderIds);
        //处理团购内容
        if(bmsDxOrders != null && bmsDxOrders.size() > 0){
            for(BmsDxOrder bmsDxOrder : bmsDxOrders){
                BmsDxGroupBuy bmsDxGroupBuy = bmsDxOrder.getBmsDxGroupBuy();
                List<BmsDxGroupBuy> bmsDxGroupBuys = new LinkedList<>();
                bmsDxGroupBuys.add(bmsDxGroupBuy);
                bmsDxGroupBuyService.postHandleGroupContent(bmsDxGroupBuys,true);
                bmsDxGroupBuyService.postHandleBusiness(bmsDxGroupBuys);
            }
        }
        return getOrderMap(bmsDxOrders);
    }

    public Map<String, Object> getRefundOrderDetail(ParamsMap paramsMap) {
        Integer userId = Integer.parseInt(paramsMap.get("userIdentify").toString());
        Integer orderId = Integer.parseInt(paramsMap.get("orderId").toString());
        Integer groupBuyUseId = Integer.parseInt(paramsMap.get("groupBuyUseId").toString());
        Integer newId = paramsMap.getInteger("newId");
        Map<String,Object> checkMap = checkOrderIsTrue(userId,orderId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        BmsDxOrder bmsDxOrder = (BmsDxOrder) checkMap.get("data");
        OrderRefundDetailRpDto orderRefundDetailRpDto = new OrderRefundDetailRpDto();
        if(newId == null) {
            Optional<BmsDxGroupBuyUse> bmsDxGroupBuyUse = bmsDxGroupBuyUseService.getBaseDao().findById(groupBuyUseId);
            if (bmsDxGroupBuyUse.isPresent()) {
                if (bmsDxGroupBuyUse.get().getOrderId().intValue() != bmsDxOrder.getId().intValue()) {
                    return ResultMapHelper.result(ResultCode.CODE_ORDER_GROUP_USE_NO_MATCH_ORDER, ResultMsg.CODE_ORDER_GROUP_USE_NO_MATCH_ORDER);
                }
                BeanUtils.copyProperties(bmsDxGroupBuyUse.get(), orderRefundDetailRpDto);
                orderRefundDetailRpDto.setRefundMoney(bmsDxGroupBuyUse.get().getGbuyActualConsum());
                orderRefundDetailRpDto.setPayWay(bmsDxOrder.getPayWay());
            }
        }else {
            Optional<BmsDxNews> bmsDxNewsOptional = bmsDxNewsService.getBaseDao().findById(newId);
            if(bmsDxNewsOptional.isPresent()) {
                BmsDxNews bmsDxNews = bmsDxNewsOptional.get();
                if (bmsDxNews.getBmsGroupBuyUseId() != null) {
                    Optional<BmsDxGroupBuyUse> bmsDxGroupBuyUse = bmsDxGroupBuyUseService.getBaseDao().findById(bmsDxNews.getBmsGroupBuyUseId());
                    if(bmsDxGroupBuyUse.isPresent()){
                        BmsDxGroupBuyUse bu = bmsDxGroupBuyUse.get();
                        Map<String, Object> conditionMap = new HashMap<>();
                        conditionMap.put("orderId", bu.getOrderId());
                        conditionMap.put("status", Constants.GROUP_REFUND_COMPLETE);
                        conditionMap.put("refundTime", bu.getRefundTime());
                        List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = bmsDxGroupBuyUseService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
                        if (bmsDxGroupBuyUse != null && bmsDxGroupBuyUses.size() > 0) {
                            BeanUtils.copyProperties(bmsDxGroupBuyUses.get(0), orderRefundDetailRpDto);
                            Double refundTotal = 0d;
                            for (BmsDxGroupBuyUse groupBuyUse : bmsDxGroupBuyUses) {
                                refundTotal = ArithUtil.add(refundTotal, groupBuyUse.getGbuyActualConsum());
                            }
                            orderRefundDetailRpDto.setRefundMoney(refundTotal);
                            orderRefundDetailRpDto.setPayWay(bmsDxOrder.getPayWay());
                        }
                    }
                }
            }
        }
        if(bmsDxOrder.getPayWay() == Constants.ALI_PAY){
            orderRefundDetailRpDto.setSerialNumber(bmsDxOrder.getPayNo());
        }else if(bmsDxOrder.getPayWay() == Constants.WX_PAY){
            orderRefundDetailRpDto.setSerialNumber(bmsDxOrder.getTransactionId());
        }
        return ResultMapHelper.success(orderRefundDetailRpDto,ResultMsg.MSG_GET_SUCCESS);
    }

    /**
     * @Description 统计用户消费总数
     * @Author: cfx
     * @Date: 2019/8/22
     */
    public Double countUserTotalConsum(Integer userId) {
        //查询优惠买单成功的
        Double total = 0d;
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("userId",userId);
        conditionMap.put("status",Constants.PAY_COMPLETE);
        Set<Integer> orderTypes = new HashSet<>();
        orderTypes.add(Constants.ONLINE_ORDER_TYPE);
        orderTypes.add(Constants.COUPONS_ORDER_TYPE);
        conditionMap.put("orderType_IN",orderTypes);
        List<BmsDxOrderStatus> bmsDxOrderStatuses = bmsDxOrderStatusService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
        if(bmsDxOrderStatuses.size() > 0){
            Set<Integer> orderIds = new HashSet<>();
            for(BmsDxOrderStatus bmsDxOrderStatus : bmsDxOrderStatuses){
                orderIds.add(bmsDxOrderStatus.getOrderId());
            }
            if(orderIds.size() > 0){
                List<BmsDxOrder> bmsDxOrders = bmsDxOrderService.getBaseDao().findByIdIn(orderIds);
                if(bmsDxOrders.size() > 0){
                    for(BmsDxOrder bmsDxOrder : bmsDxOrders){
                        total = ArithUtil.add(total,ArithUtil.add(bmsDxOrder.getActualConsum(),bmsDxOrder.getDiscountConsum() == null ? 0d : bmsDxOrder.getDiscountConsum()));
                    }
                }
            }
        }
        //查询团购买单成功的
        total = ArithUtil.add(total,bmsDxGroupBuyUseService.getBaseDao().countGroupBuyUseByUserId(userId,Constants.GROUP_ALREADY_USE));
        return total;
    }


    /**
     * @Description 统计用户消费总笔数(按订单来算)
     * @Author: cfx
     * @Date: 2019/8/22
     */
    public Integer countUserTotalNum(Integer userId) {
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("userId",userId);
        conditionMap.put("status",Constants.PAY_COMPLETE);
        Set<Integer> orderTypes = new HashSet<>();
        orderTypes.add(Constants.ONLINE_ORDER_TYPE);
        orderTypes.add(Constants.COUPONS_ORDER_TYPE);
        conditionMap.put("orderType_IN",orderTypes);
        List<BmsDxOrderStatus> bmsDxOrderStatuses = bmsDxOrderStatusService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
        return bmsDxOrderStatuses.size();
    }



    public Map<String, Object> findIsBuySameGroupBuy(Map<String, Object> paramsMap) {
        String userIdentify = paramsMap.get("userIdentify").toString();
        Integer userId = Integer.parseInt(userIdentify);
        Integer groupBuyId = Integer.parseInt(paramsMap.get("groupBuyId").toString());
        List<BmsDxOrder> bmsDxOrders = bmsDxOrderDao.selfFindCommitGroupBuyOrder(userId,groupBuyId);
        return ResultMapHelper.success(bmsDxOrders,ResultMsg.MSG_GET_SUCCESS);
    }


    public Map<String, Object> orderCommit_V3(ParamsMap paramsMap) {
        RequestHeaderData headerData = new  RequestHeaderData();
        final int FIVE_FULL_COUPON = 5;
        final int EIGHT_FULL_COUPON = 8;
        final Map<Integer,Integer> fullCouponUseNumLimitMap = new HashMap<Integer,Integer>(){{
            put(FIVE_FULL_COUPON,80);
            put(EIGHT_FULL_COUPON,50);
        }};
        String userIdentify = paramsMap.get("userIdentify").toString();
        Integer orderType = Integer.parseInt(paramsMap.get("orderType").toString());
        Integer businessId = paramsMap.getInteger("businessId");
        Integer userId = Integer.parseInt(userIdentify);
        Integer userFullCouponId = paramsMap.getInteger("userFullCouponId");
        Integer backCardId = paramsMap.getInteger("backCardId");
        Double useCardMoney = paramsMap.getDouble("useCardMoney");
        Integer reId = paramsMap.getInteger("reId");
        Integer thirdChannel = paramsMap.getInteger("thirdChannel");

        //Integer qs = Integer.parseInt(paramsMap.get("qs").toString());
        BmsDxOrder bmsDxOrder = new BmsDxOrder();
        if(thirdChannel != null && thirdChannel == Constants.THIRD_CHANNEL_ZHT){
            bmsDxOrder.setCreateWay(Constants.ZHUHAITONG);
        }
        Date nowTime = new Date();
        Optional<BmsBusiness> businessOptional = bmsBusinessService.getBaseDao().findById(businessId);
        if(!businessOptional.isPresent()){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST,ResultMsg.CODE_BUSINESS_NO_EXIST);
        }
        Integer isCanrevisionPrice = 0;  //无需改价
        BmsBusiness business = businessOptional.get();
        BmsFullCoupon bmsFullCoupon = null;
        BmsUserReceCoupon bmsUserReceCoupon = null;
        BmsBusinessCoupon businessCoupon = null;
        BmsBackCard bmsBackCard = null;
        List<BmsThirdCode> bmsThirdCodes = null;
        if(userFullCouponId != null){
            Optional<BmsUserReceCoupon> bmsUserReceCouponOptional = bmsUserReceCouponService.getBaseDao().findById(userFullCouponId);
            if(!bmsUserReceCouponOptional.isPresent()){
                return ResultMapHelper.result(ResultCode.CODE_FULL_COUPON_IS_NO_EXIST,ResultMsg.CODE_FULL_COUPON_IS_NO_EXIST);
            }
            bmsUserReceCoupon = bmsUserReceCouponOptional.get();
            if(bmsUserReceCoupon.getStatus() == Constants.COMMON_FLAG_TRUE_INT){
                return ResultMapHelper.result(ResultCode.CODE_FULL_COUPON_IS_USE,ResultMsg.CODE_FULL_COUPON_IS_USE);
            }
            if(bmsUserReceCoupon.getBusinessId() != null) {
                if (bmsUserReceCoupon.getBusinessId().intValue() != business.getId().intValue()) {
                    return ResultMapHelper.result(ResultCode.CODE_FULL_COUPON_IS_NO_BELONG, ResultMsg.CODE_FULL_COUPON_IS_NO_BELONG);
                }
            }
            Integer expireTime = DateTimeUtils.converDateToInterger(bmsUserReceCoupon.getExpireTime());;
            if(bmsUserReceCoupon.getType() == Constants.ACTIVITY_PRODUCE){
                expireTime = DateTimeUtils.converDateToInterger(DateTimeUtils.addDay(bmsUserReceCoupon.getExpireTime(),1));
            }
            if(DateTimeUtils.converDateToInterger(nowTime).intValue() > expireTime.intValue()){
                return ResultMapHelper.result(ResultCode.CODE_FULL_COUPON_IS_EXPIRE,ResultMsg.CODE_FULL_COUPON_IS_EXPIRE);
            }
            bmsFullCoupon = bmsUserReceCoupon.getBmsFullCoupon();
            businessCoupon = bmsUserReceCoupon.getBmsBusinessCoupon();
            if(bmsFullCoupon == null && businessCoupon == null){
                return ResultMapHelper.result(ResultCode.CODE_FULL_COUPON_IS_USE,ResultMsg.CODE_FULL_COUPON_IS_USE);
            }
            //判断是否超过小时限制
            if(bmsFullCoupon != null && businessCoupon == null) {
                String[] fullRule = bmsFullCoupon.getFullRule().split("_");
                String redisKey = Constants.REDIS_KEY_FULL_COUPON_USE_NUM + bmsFullCoupon.getId();
                if (redisTemplate.hasKey(redisKey)) {
                    Integer useNum = Integer.parseInt(redisTemplate.opsForValue().get(redisKey).toString());
                    Integer fullMoney = Integer.parseInt(fullRule[1]);
                    if (fullCouponUseNumLimitMap.containsKey(fullMoney)) {
                        if (useNum.intValue() >= fullCouponUseNumLimitMap.get(fullMoney).intValue()) {
                            return ResultMapHelper.result(ResultCode.CODE_FULL_COUPON_IS_MORE, ResultMsg.CODE_FULL_COUPON_IS_MORE);
                        }
                    }
                }
            }
        }
        if(backCardId != null){
            if(useCardMoney != null && useCardMoney > 0d) {
                bmsBackCard = bmsBackCardService.getBaseDao().findByIdAndIsOpen(backCardId, Constants.COMMON_FLAG_TRUE_INT);
                if (bmsBackCard == null) {
                    return ResultMapHelper.result(ResultCode.CODE_ORDER_BACK_NO, ResultMsg.CODE_ORDER_BACK_NO);
                }
                if (bmsBackCard.getTotal() < useCardMoney) {
                    return ResultMapHelper.result(ResultCode.CODE_ORDER_BACK_NO_USE_MONEY, ResultMsg.CODE_ORDER_BACK_NO_USE_MONEY);
                }
                //判断返现卡是否过期
                if (bmsBackCardService.checkBackCardExpireTime(bmsBackCard)) {
                    return ResultMapHelper.result(ResultCode.CODE_ORDER_BACK_EXPIRE, ResultMsg.CODE_ORDER_BACK_EXPIRE);
                }
            }
        }
        BmsDxGroupBuy bmsDxGroupBuy = null;
        Double discountConsum = 0d;
        OrderCommitHolder orderCommitHolder = new OrderCommitHolder();

        if(orderCommitServiceMap.containsKey(orderType)){
            orderCommitHolder.setBmsDxOrder(bmsDxOrder);
            orderCommitHolder.setParamsMap(paramsMap);
            OrderCommitService orderCommitService = orderCommitServiceMap.get(orderType);
            orderCommitHolder = orderCommitService.commitLogic(orderCommitHolder);
            Map<String,Object> executionResult = orderCommitHolder.getExecutionResult();
            if(!(executionResult.containsKey("status") && ResultCode.CODE_NORMAL.equals(executionResult.get("status").toString()))){
                return executionResult;
            }
        }else {
            /*if (orderType == onlinePay) {
                Map<String, Object> checkMap = RequestParamUtils.checkParams(paramsMap, "totalConsum", "actualConsum");
                if (!(checkMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString()))) {
                    return checkMap;
                }
                Double totalConsum = Double.parseDouble(paramsMap.get("totalConsum").toString());
                Double actualConsum = totalConsum;
                Double shopConsum = ArithUtil.mul(actualConsum, Constants.SEETLE_LINES);
                Double settleMoney = ArithUtil.mul(actualConsum, Constants.SEETLE_LINES);
                bmsDxOrder.setTotalConsum(totalConsum);
                bmsDxOrder.setActualConsum(actualConsum);
                bmsDxOrder.setSettleMoney(settleMoney);
                bmsDxOrder.setShopConsum(shopConsum);
            } else*/
            if (orderType == offerToPay) {
                Map<String, Object> checkMap = RequestParamUtils.checkParams(paramsMap, "totalConsum",
                        "actualConsum", "noJoinConsum", "couponId");
                if (!(checkMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString()))) {
                    return checkMap;
                }
                Double totalConsum = Double.parseDouble(paramsMap.get("totalConsum").toString());
                if(totalConsum < 0d) {
                    return ResultMapHelper.result(ResultCode.CODE_ERROR_100, "买单金额必须大于0");
                }
                Double actualConsum = Double.parseDouble(paramsMap.get("actualConsum").toString());
                Double noJoinConsum = Double.parseDouble(paramsMap.get("noJoinConsum").toString());
                Integer couponId = Integer.parseInt(paramsMap.get("couponId").toString());
                Optional<BmsDxCoupon> bmsDxCouponOp = bmsDxCouponService.getBaseDao().findById(couponId);
                if (!bmsDxCouponOp.isPresent()) {
                    return ResultMapHelper.result(ResultCode.CODE_ORDER_ONLINEPAY_NO_EXIST, ResultMsg.CODE_ORDER_ONLINEPAY_NO_EXIST);
                }
                BmsDxCoupon bmsDxCoupon = bmsDxCouponOp.get();
                if (bmsDxCoupon.getUseNum() != Constants.COMMON_FLAG_FALSE_INT) {
                    //有使用次数限制，查询当前用户是否达到使用次数
                    Integer num = bmsDxOrderDao.countUserUseCouponNum(userId, couponId);
                    System.out.println(num);
                    if (num.intValue() >= bmsDxCoupon.getUseNum()) {
                        return ResultMapHelper.result(ResultCode.CODE_ORDER_ONLINEPAY_MAX, ResultMsg.CODE_ORDER_ONLINEPAY_MAX);
                    }
                }
                double calAmount = ArithUtil.sub(totalConsum, noJoinConsum);
                double discount = ArithUtil.div(Double.parseDouble(bmsDxCoupon.getPayContent()), 10d);
                double discountMoney = ArithUtil.mul(calAmount, discount);
                actualConsum = ArithUtil.add(noJoinConsum, discountMoney);
                Double shopConsum = ArithUtil.mul(actualConsum, Constants.SEETLE_LINES);
                Double settleMoney = ArithUtil.mul(actualConsum, Constants.SEETLE_LINES);
                Double preferentialMoney = calAmount - discountMoney;
                bmsDxOrder.setTotalConsum(totalConsum);
                bmsDxOrder.setActualConsum(actualConsum);
                bmsDxOrder.setNoJoinConsum(noJoinConsum);
                bmsDxOrder.setBmsCouponId(couponId);
                bmsDxOrder.setSettleMoney(settleMoney);
                bmsDxOrder.setShopConsum(shopConsum);
                bmsDxOrder.setPreferentialMoney(preferentialMoney);
            } else if (orderType == groupBuyingPay) {
                Map<String, Object> checkMap = RequestParamUtils.checkParams(paramsMap, "groupBuyNum", "groupBuyId");
                if (!(checkMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString()))) {
                    return checkMap;
                }
                Integer groupBuyId = Integer.parseInt(paramsMap.get("groupBuyId").toString());
                Integer groupBuyNum = Integer.parseInt(paramsMap.get("groupBuyNum").toString());
                bmsDxGroupBuy = bmsDxGroupBuyService.getGroupBuyById(groupBuyId);
                if (bmsDxGroupBuy == null) {
                    return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST_GROUP_BUY, ResultMsg.CODE_BUSINESS_NO_EXIST_GROUP_BUY);
                }
                bmsDxOrder.setBmsDxGroupBuy(bmsDxGroupBuy);
                if(bmsDxGroupBuy.getLeastBuyNum() != null && bmsDxGroupBuy.getLeastBuyNum() > 0) {
                    if(groupBuyNum < bmsDxGroupBuy.getLeastBuyNum()){
                        return ResultMapHelper.result(ResultCode.CODE_ERROR_100, ResultMsg.MSG_LEAST_BUY_NUM);
                    }
                }
                if (!(bmsDxGroupBuy.getStatus() == Constants.COMMON_FLAG_TRUE_INT)) {
                    return ResultMapHelper.result(ResultCode.CODE_BUSINESS_GROUOP_AL_OFFLINE, ResultMsg.CODE_BUSINESS_GROUOP_AL_OFFLINE);
                }
                //判断该团购是否过期
                if (bmsDxGroupBuy.getExpireTime() != null) {
                    Date overTime = DateTimeUtils.addDay(bmsDxGroupBuy.getExpireTime(), 1);
                    if (nowTime.getTime() >= overTime.getTime()) {
                        return ResultMapHelper.result(ResultCode.CODE_BUSINESS_GROUP_EXPIRE, ResultMsg.CODE_BUSINESS_GROUP_EXPIRE);
                    }
                }
                //判断该团购券是否属于商家
                if (bmsDxGroupBuy.getBusinessId() != businessId.intValue()) {
                    return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_BELONG, ResultMsg.CODE_BUSINESS_NO_BELONG);
                }
                //判断是否是特特乐团购，需要锁库存
                if (bmsDxGroupBuy.getGroupType() != null && bmsDxGroupBuy.getGroupType() == Constants.GROUP_TYPE_TETE) {
                /*String redisKey = Constants.REDIS_KEY_BUINESS_ID + bmsDxGroupBuy.getBusinessId();
                //使用特特乐团购加锁
                if (!(RedisTemplateUtils.addLock(redisKey, RedisTemplateUtils.GEN_TRY_NUM))) {
                    return ResultMapHelper.result(ResultCode.CODE_ORDER_PLACE_FAIL, ResultMsg.CODE_ORDER_PLACE_FAIL);
                }
                paramsMap.put("lockBusinessId", redisKey);*/
                    //判断是否到抢购时间
                    if (bmsDxGroupBuy.getStartSellTime() != null) {
                        if (DateTimeUtils.converDateToInterger(nowTime) < DateTimeUtils.converDateToInterger(bmsDxGroupBuy.getStartSellTime())) {
                            return ResultMapHelper.result(ResultCode.CODE_GROUP_NO_CAN_BUY, ResultMsg.CODE_GROUP_NO_CAN_BUY);
                        }
                    }
                    //判断抢购时间是否过期
                    if (bmsDxGroupBuy.getLimitBuyTime() != null) {
                        if (DateTimeUtils.converDateToInterger(nowTime) >= DateTimeUtils.converDateToInterger(bmsDxGroupBuy.getLimitBuyTime())) {
                            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_GROUP_EXPIRE, ResultMsg.CODE_BUSINESS_GROUP_EXPIRE);
                        }
                    }
                    //锁当前团购套餐的库存
                    bmsThirdCodes = bmsThirdCodeService.checkUseCodeHavingUseNum(businessId, groupBuyId, groupBuyNum);
                    if (!(bmsThirdCodes != null && bmsThirdCodes.size() == groupBuyNum)) {
                        //库存不足，下架团购
                        //bmsDxGroupBuy.setStatus(Constants.OFFLINE_STATUS);
                        //bmsDxGroupBuy.setOfflineTime(nowTime);
                        //bmsDxGroupBuy.set
                        return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NOT_ENOUGH, ResultMsg.CODE_BUSINESS_NOT_ENOUGH);
                    }
                }
                if(bmsDxGroupBuy.getIsTimeLimit() != null && bmsDxGroupBuy.getIsTimeLimit() == Constants.COMMON_FLAG_TRUE_INT){
                    Date startSellTime = bmsDxGroupBuy.getStartSellTime();
                    Date limitBuyTime = bmsDxGroupBuy.getLimitBuyTime();
                    if(startSellTime != null && DateTimeUtils.match(nowTime,startSellTime,DateTimeUtils.MATCH_MODEL_LT)){
                        return ResultMapHelper.result(ResultCode.CODE_ERROR_100, ResultMsg.MSG_NOT_TIME_FOR_SALE);
                    }
                    if(limitBuyTime != null && DateTimeUtils.match(nowTime,limitBuyTime,DateTimeUtils.MATCH_MODEL_GT)){
                        return ResultMapHelper.result(ResultCode.CODE_ERROR_100, ResultMsg.MSG_BUY_TIME_OVER);
                    }
                }
                //是否超过团购券限制购买数量
                if (bmsDxGroupBuy.getLimitBuyNum() != null && bmsDxGroupBuy.getLimitBuyNum() > 0) {
                    //查询当前用户已经买了多少张这个团购券
                    Integer userAlreadyBuyNum = bmsDxGroupBuyUseService.getUserBuyNum(userId, bmsDxGroupBuy.getId());
                    if (groupBuyNum > (bmsDxGroupBuy.getLimitBuyNum() - userAlreadyBuyNum)) {
                        return ResultMapHelper.result(ResultCode.CODE_BUSINESS_OVER_NUM, ResultMsg.CODE_BUSINESS_OVER_NUM);
                    }
                }
                if (bmsDxGroupBuy.getSellInventory() != null) {
                    String redisKey = Constants.REDIS_KEY_BUINESS_GROUP_BUY + bmsDxGroupBuy.getId();
                    boolean addLockResult = RedisTemplateUtils.addLock(redisKey, RedisTemplateUtils.GEN_TRY_NUM);
                    if (!addLockResult) {
                        return ResultMapHelper.result(ResultCode.CODE_ORDER_PLACE_FAIL, ResultMsg.CODE_ORDER_PLACE_FAIL);
                    }
                    paramsMap.put("isAddLock", redisKey);
                    Integer num = bmsDxGroupBuyService.getBaseDao().countGroupBuySellNum(groupBuyId);
                    if (groupBuyNum > num) {
                        return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NOT_ENOUGH, ResultMsg.CODE_BUSINESS_NOT_ENOUGH);
                    }
                    bmsDxGroupBuy.setSellInventory(num - groupBuyNum);
                }
                Double totalConsum = ArithUtil.mul(groupBuyNum, bmsDxGroupBuy.getGroupPrice());
                Double actualConsum = totalConsum;
                bmsDxOrder.setBmsGroupBuyId(bmsDxGroupBuy.getId());
                bmsDxOrder.setGroupBuyNum(groupBuyNum);
                bmsDxOrder.setTotalConsum(totalConsum);
                bmsDxOrder.setActualConsum(actualConsum);
                if(reId != null) {
                    Map<String, Object> shopList = new HashMap<>();
                    shopList.put("reId", reId);
                    bmsDxOrder.setRemark(JSON.toJSONString(shopList));
                }
            } else if (orderType == Constants.GROUP_BUY_BARGAIN_ORDER_TYPE) {
                Map<String, Object> checkMap = RequestParamUtils.checkParams(paramsMap, "groupBuyNum", "groupBuyId");
                if (!(checkMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString()))) {
                    return checkMap;
                }
                Integer groupBuyId = Integer.parseInt(paramsMap.get("groupBuyId").toString());
                Integer groupBuyNum = Integer.parseInt(paramsMap.get("groupBuyNum").toString());
                bmsDxGroupBuy = bmsDxGroupBuyService.getGroupBuyById(groupBuyId);
                if (bmsDxGroupBuy == null) {
                    return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST_GROUP_BUY, ResultMsg.CODE_BUSINESS_NO_EXIST_GROUP_BUY);
                }
                bmsDxOrder.setBmsDxGroupBuy(bmsDxGroupBuy);
                if (!(bmsDxGroupBuy.getStatus() == Constants.COMMON_FLAG_TRUE_INT)) {
                    return ResultMapHelper.result(ResultCode.CODE_BUSINESS_GROUOP_AL_OFFLINE, ResultMsg.CODE_BUSINESS_GROUOP_AL_OFFLINE);
                }
                //判断该团购是否过期
                if (bmsDxGroupBuy.getExpireTime() != null) {
                    Date overTime = DateTimeUtils.addDay(bmsDxGroupBuy.getExpireTime(), 1);
                    if (nowTime.getTime() >= overTime.getTime()) {
                        return ResultMapHelper.result(ResultCode.CODE_BUSINESS_GROUP_EXPIRE, ResultMsg.CODE_BUSINESS_GROUP_EXPIRE);
                    }
                }
                //判断该团购券是否属于商家
                if (bmsDxGroupBuy.getBusinessId() != businessId.intValue()) {
                    return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_BELONG, ResultMsg.CODE_BUSINESS_NO_BELONG);
                }
                //是否超过团购券限制购买数量
                if (bmsDxGroupBuy.getLimitBuyNum() != null) {
                    //查询当前用户已经买了多少张这个团购券
                    Integer userAlreadyBuyNum = bmsDxGroupBuyUseService.getUserBuyNum(userId, bmsDxGroupBuy.getId());
                    if (groupBuyNum > (bmsDxGroupBuy.getLimitBuyNum() - userAlreadyBuyNum)) {
                        return ResultMapHelper.result(ResultCode.CODE_BUSINESS_OVER_NUM, ResultMsg.CODE_BUSINESS_OVER_NUM);
                    }
                }
                if (bmsDxGroupBuy.getSellInventory() != null) {
                    String redisKey = Constants.REDIS_KEY_BUINESS_GROUP_BUY + bmsDxGroupBuy.getId();
                    boolean addLockResult = RedisTemplateUtils.addLock(redisKey, RedisTemplateUtils.GEN_TRY_NUM);
                    if (!addLockResult) {
                        return ResultMapHelper.result(ResultCode.CODE_ORDER_PLACE_FAIL, ResultMsg.CODE_ORDER_PLACE_FAIL);
                    }
                    paramsMap.put("isAddLock", redisKey);
                    Integer num = bmsDxGroupBuyService.getBaseDao().countGroupBuySellNum(groupBuyId);
                    if (groupBuyNum > num) {
                        return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NOT_ENOUGH, ResultMsg.CODE_BUSINESS_NOT_ENOUGH);
                    }
                    bmsDxGroupBuy.setSellInventory(num - groupBuyNum);
                }
                if (bmsDxGroupBuy.getLimitOnceBuyNum() != null) {
                    if (groupBuyNum > bmsDxGroupBuy.getLimitOnceBuyNum()) {
                        return ResultMapHelper.result(ResultCode.CODE_BUSINESS_OVER_NUM, ResultMsg.CODE_BUSINESS_OVER_NUM);
                    }
                }
                Double totalConsum = ArithUtil.mul(groupBuyNum, bmsDxGroupBuy.getGroupPrice());
                //判断是否是砍价团购
                Integer bargainId = paramsMap.getInteger("bargainId");
                BmsUserBargain bmsUserBargain;
                if (bargainId == null) {
                    bmsUserBargain = new BmsUserBargain();
                    bmsUserBargain.setUserId(userId);
                    bmsUserBargain.setStartPrice(bmsDxGroupBuy.getGroupPrice());
                    bmsUserBargain.setFinallyPrice(bmsDxGroupBuy.getGroupPrice());
                    bmsUserBargain.setGroupBuyId(groupBuyId);
                    bmsUserBargain.setBusinessId(businessId);
                    bmsUserBargain.setNewTime(nowTime);
                    bmsUserBargain.setExpireTime(DateTimeUtils.addDay(nowTime, 1));
                    bmsUserBargainService.getBaseDao().save(bmsUserBargain);
                } else {
                    bmsUserBargain = bmsUserBargainService.getBargainById(bargainId);
                }
                if (bmsUserBargain == null) {
                    return ResultMapHelper.result(BargainGroupBuyEnums.BARGAIN_NO_EXIST);
                }
                if (DateTimeUtils.converDateToInterger(nowTime) >= DateTimeUtils.converDateToInterger(bmsUserBargain.getExpireTime())) {
                    return ResultMapHelper.result(BargainGroupBuyEnums.BARGAIN_NO_EXIST);
                }
                if (bmsUserBargain.getUserId().intValue() != userId.intValue()) {
                    return ResultMapHelper.result(BargainGroupBuyEnums.BARGAIN_NO_BELONG);
                }
                bmsUserBargain.setOverTime(nowTime);
                bmsUserBargain.setExpireTime(nowTime);
                bmsUserBargain.setProState(BmsUserBargainService.EXPIRE_STATUS);
                orderCommitHolder.setBmsUserBargain(bmsUserBargain);
                bmsDxOrder.setBargainId(bmsUserBargain.getId());
                Double actualConsum = bmsUserBargain.getFinallyPrice();
                bmsDxOrder.setBmsGroupBuyId(bmsDxGroupBuy.getId());
                bmsDxOrder.setGroupBuyNum(groupBuyNum);
                bmsDxOrder.setTotalConsum(totalConsum);
                bmsDxOrder.setActualConsum(actualConsum);
            } else if (orderType == Constants.LOCAL_LIFE_ORDER_TYPE) {
                Double totalConsum = 0d;
                List<BmsLocalLifeGoodsVo> shopList = JSONObject.parseArray(paramsMap.getString("shopList"), BmsLocalLifeGoodsVo.class);
                for (BmsLocalLifeGoodsVo goods : shopList) {
                    Integer num = goods.getNum();
                    Optional<BmsLocalLifeGoods> lifeGoodsOptional = bmsLocalLifeGoodsService.getBaseDao().findById(goods.getGoodId());
                    if (lifeGoodsOptional.isPresent()) {
                        BmsLocalLifeGoods bmsLocalLifeGoods = lifeGoodsOptional.get();
                        // TODO 本地生活商品已经被删除，下单时做限制
                        if(bmsLocalLifeGoods.getIsDelete() == Constants.COMMON_FLAG_TRUE_INT){
                            return ResultMapHelper.failure("选购商品中已有商品被移除，请重新选购");
                        }
                        totalConsum += num * (lifeGoodsOptional.get().getGoodsPrice());
                    }
                }
                if (bmsBackCard != null) {
                    if (useCardMoney >= totalConsum) {
                        useCardMoney = totalConsum;
                    }
                }
                bmsDxOrder.setTotalConsum(totalConsum);
                bmsDxOrder.setActualConsum(totalConsum);
                bmsDxOrder.setChangePrice(totalConsum);
                bmsDxOrder.setShopList(JSON.toJSONString(shopList));
                bmsDxOrder.setRemark(paramsMap.getString("remark"));
                bmsDxOrder.setIsTake(paramsMap.getInteger("isTake"));
                Integer lifeId = paramsMap.getInteger("lifeId");
                BmsLocalLife bmsLocalLife = bmsLocalLifeService.getBaseDao().findById(lifeId).get();
                isCanrevisionPrice = bmsLocalLife.getIsCanrevisionPrice() == null ? 0 : bmsLocalLife.getIsCanrevisionPrice();
                if (isCanrevisionPrice != 1) {
                    bmsDxOrder.setIsChangePrice(Constants.COMMON_FLAG_TRUE_INT);
                } else {
                    bmsDxOrder.setIsChangePrice(Constants.COMMON_FLAG_FALSE_INT);
                }
                bmsDxOrder.setLifeId(lifeId);
                if (paramsMap.getInteger("isTake") != null && paramsMap.getInteger("isTake") == 0) {
                    Map<String, Object> infoMap = JSON.parseObject(paramsMap.get("userInfo").toString());
                /*List<BmsUserLifeInfo> bmsUserLifeInfoList = bmsUserLifeInfoService.findByUserId(userId);
                if (bmsUserLifeInfoList.size() > 0) {
                    bmsUserLifeInfo = bmsUserLifeInfoList.get(0);
                }*/
                    BmsUserLifeInfo bmsUserLifeInfo = new BmsUserLifeInfo();
                    BeanUtils.populate(bmsUserLifeInfo, infoMap);
                    bmsUserLifeInfo.setUserId(userId);
                    bmsUserLifeInfoService.getBaseDao().save(bmsUserLifeInfo);
                    bmsDxOrder.setShipInfo(bmsUserLifeInfo.getId());
                } else {
                    isCanrevisionPrice = 0;
                    bmsDxOrder.setIsChangePrice(Constants.COMMON_FLAG_TRUE_INT);
                }
            } else if (orderType == Constants.PLATFORM_ORDER_TYPE) {
                //orderCommitHolder.setParamsMap(paramsMap);
                //orderCommitHolder.setBmsDxOrder(bmsDxOrder);
                //plateformOrderCommit(orderCommitHolder);
                Map<String, Object> checkMap = RequestParamUtils.checkParams(paramsMap, "goodNum", "goodId", "address", "buyArea");
                if (!(checkMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString()))) {
                    return checkMap;
                }
                Integer goodId = paramsMap.getInteger("goodId");
                String address = paramsMap.getString("address");
                Integer buyArea = paramsMap.getInteger("buyArea");
                BmsPlatformGood bmsPlatformGood = bmsPlatformGoodService.findById(goodId);
                //购买数量
                Integer num = paramsMap.getInteger("goodNum");
                if (bmsPlatformGood == null) {
                    return ResultMapHelper.result(PlatformGoodEnum.PLATFORM_GOOD_NO_EXIST);
                }
                if (bmsPlatformGood.getIsOff() == Constants.COMMON_FLAG_TRUE_INT) {
                    return ResultMapHelper.result(PlatformGoodEnum.PLATFORM_GOOD_IS_OFF);
                }
                if (bmsPlatformGood.getInventory() <= 0) {
                    return ResultMapHelper.result(PlatformGoodEnum.CODE_PLATFORM_GOOD_SELL_FIN);
                }
                if (bmsPlatformGood.getInventory() < num) {
                    return ResultMapHelper.result(PlatformGoodEnum.PLATFORM_GOOD_INV_NO);
                }
                if (bmsPlatformGood.getIsLimitBuyDay() == Constants.COMMON_FLAG_TRUE_INT) {
                    //查看今天买了没
                    if (redisTemplate.hasKey(Constants.REDIS_KEY_TODAY_BUY + userId + ":" + bmsPlatformGood.getId())) {
                        return ResultMapHelper.result(PlatformGoodEnum.PLATFORM_GOOD_TODAY_BUY);
                    }
                }
                //一天最多买多少件
                if (bmsPlatformGood.getLimitSellOnce() != Constants.COMMON_FLAG_FALSE_INT) {
                    if (num > bmsPlatformGood.getLimitSellOnce()) {
                        return ResultMapHelper.result(PlatformGoodEnum.PLATFORM_GOOD_BUY_LIMIT);
                    }
                }
                //总共可购买多少件
                if (bmsPlatformGood.getLimitSell() != Constants.COMMON_FLAG_FALSE_INT) {
                    String limitRedisKey = Constants.REDIS_KEY_PLATFORM_ALREADY_BUY;
                    Double alBuy = null;
                    if(redisTemplate.hasKey(limitRedisKey)) {
                        alBuy = redisTemplate.opsForZSet().score(limitRedisKey, "user:" + userId);
                    }else {
                        //alBuy = this.findUserBuyMaskNum(userId);
                    }
                    if (alBuy != null) {
                        Integer alreadyBuyNum = alBuy.intValue() + num;
                        if (alreadyBuyNum > bmsPlatformGood.getLimitSell()) {
                            return ResultMapHelper.result(PlatformGoodEnum.PLATFORM_GOOD_BUY_LIMIT);
                        }
                    }
                }
                Integer count = 0;
                Integer updateRow;
                boolean isCanGet = false;
                while (true) {
                    updateRow = bmsPlatformGoodService.updateInventoryNum(bmsPlatformGood.getId(), num, bmsPlatformGood.getVersion());
                    if (updateRow == 1) {
                        isCanGet = true;
                        break;
                    }
                    entityManager.unwrap(Session.class).evict(bmsPlatformGood);
                    bmsPlatformGood = bmsPlatformGoodService.findById(bmsPlatformGood.getId());
                    if (bmsPlatformGood.getInventory() <= 0) {
                        return ResultMapHelper.result(PlatformGoodEnum.CODE_PLATFORM_GOOD_SELL_FIN);
                    }
                    if (bmsPlatformGood.getInventory() < num) {
                        return ResultMapHelper.result(PlatformGoodEnum.PLATFORM_GOOD_INV_NO);
                    }
                    if (count >= 100) {
                        break;
                    }
                    count++;
                }
                //String uuid = WebUtils.getUUId();
                //boolean isCanGet = RedisTemplateUtils.addLockCanWait("good:" + goodId,uuid,5);
              /*paramsMap.put("goodLock","good:" + goodId);
            Integer kucun = Integer.parseInt(redisTemplate.opsForValue().get("good:id").toString());
            if(kucun < num){
                return ResultMapHelper.result(PlatformGoodEnum.PLATFORM_GOOD_INV_NO);
            }
            kucun = kucun - num;
            redisTemplate.opsForValue().set("good:id",kucun);*/
                //得到库存,计算金额
                //往redis里设置库存
                //threadLocal.set(uuid);
                //String uuid = WebUtils.getUUId();
                if (!isCanGet) {
                    return ResultMapHelper.result(ActivityEnums.SYS_DELAY);
                }
                String redisKey = Constants.REDIS_KEY_PLATFORM_GOOD_IN;
                String uuid = WebUtils.getUUId();
                redisTemplate.opsForZSet().incrementScore(redisKey, uuid + ":" + goodId, num);
                orderCommitHolder.getUserData().put("platformNumRedisKey", uuid);
                Double totalConsum = ArithUtil.mul(num, bmsPlatformGood.getGoodPrice());
                if (buyArea == BmsPlatformGoodService.MASK_ID_OUT) {
                    totalConsum = ArithUtil.mul(num, bmsPlatformGood.getGoodPriceOut());
                }
                Double actualConsum = totalConsum;
                bmsDxOrder.setPlatformBuyNum(num);
                bmsDxOrder.setPlatformGoodId(bmsPlatformGood.getId());
                bmsDxOrder.setTotalConsum(totalConsum);
                bmsDxOrder.setActualConsum(actualConsum);
                Map<String, Object> shopList = new HashMap<>();
                shopList.put("address", address);
                bmsDxOrder.setShopList(JSON.toJSONString(shopList));
            } else {
                return ResultMapHelper.result(ResultCode.CODE_ORDER_TYPE_ERROR, ResultMsg.CODE_ORDER_TYPE_ERROR);
            }
        }
        //如果有优惠的情况
        Double reduction = 0d;
        if(bmsFullCoupon != null){
            //满减规则
            String[] fullRule = bmsFullCoupon.getFullRule().split("_");
            //触发金额
            Double fullMoney = Double.parseDouble(fullRule[0]);
            //是否有无门槛
            if(bmsFullCoupon.getIsThhold() == Constants.FULL_COUPON_HAVE_THHOLD) {
                if (bmsDxOrder.getTotalConsum() < fullMoney) {
                    return ResultMapHelper.result(ResultCode.CODE_FULL_COUPON_ILLEGAL, ResultMsg.CODE_FULL_COUPON_ILLEGAL);
                }
            }
            reduction = Double.parseDouble(fullRule[1]);
            bmsDxOrder.setFullCouponId(userFullCouponId);
            bmsUserReceCoupon.setStatus(Constants.COMMON_FLAG_TRUE_INT);
            bmsUserReceCoupon.setUseTime(nowTime);
        }else if(businessCoupon != null){
            if(businessCoupon.getStartTime().getTime() > nowTime.getTime()){
                return ResultMapHelper.result(ResultCode.CODE_ORDER_GROUP_NO_TO_USE_TIME,ResultMsg.CODE_ORDER_GROUP_NO_TO_USE_TIME);
            }
            String content = businessCoupon.getCouponContent();
            Map<String,Object> contentMap = JSON.parseObject(content);
            //触发金额
            reduction = Double.parseDouble(contentMap.get("amount").toString());
            bmsDxOrder.setFullCouponId(userFullCouponId);
            bmsUserReceCoupon.setStatus(Constants.COMMON_FLAG_TRUE_INT);
            bmsUserReceCoupon.setUseTime(nowTime);
        }

        //处理抵扣分销余额
        Double useFxMoney = paramsMap.getDouble("useFxMoney");
        Integer fxRole = fxCenterService.getFxRole(userId);
        if(useFxMoney != null){
            reduction = ArithUtil.add(reduction,useFxMoney);

            UseFxMoenyDto useFxMoenyDto = new UseFxMoenyDto();
            useFxMoenyDto.setUserId(userId);
            useFxMoenyDto.setUseMoney(useFxMoney);
            useFxMoenyDto.setFxRole(fxRole);

            bmsDxOrder.setUseFxMoney(useFxMoney);

            Map<String, Object> useFxMoneyMap = fxCenterService.useFxMoney(useFxMoenyDto);
            if(useFxMoneyMap.get("status") != null && !useFxMoneyMap.get("status").equals("00")){
                return useFxMoneyMap;
            }
        }

        if(bmsBackCard != null){
            bmsBackCard.setTotal(ArithUtil.sub(bmsBackCard.getTotal(),useCardMoney));
            //注重优先级
            if(bmsBackCard.getCompaySet() != null){
                bmsBackCard.setCompaySet(ArithUtil.sub(bmsBackCard.getCompaySet(),useCardMoney));
                if(bmsBackCard.getCompaySet() < 0d){
                    bmsBackCard.setCompaySet(0d);
                }
            }
            reduction = ArithUtil.add(reduction,useCardMoney);
            bmsDxOrder.setUseCardMoney(useCardMoney);
            bmsDxOrder.setBackCardId(backCardId);
        }
        //优惠金额
        discountConsum = reduction;
        //用户实付金额
        bmsDxOrder.setActualConsum(ArithUtil.sub(bmsDxOrder.getActualConsum(),reduction));
        if(orderType == onlinePay || orderType == offerToPay){
            //程序分账金额
            bmsDxOrder.setSettleMoney(ArithUtil.sub(bmsDxOrder.getShopConsum(),reduction));
            if(bmsDxOrder.getSettleMoney() > 0d) {
                //shopConsum = ArithUtil.add(shopConsum,settleMoney);
                bmsDxOrder.setSettleMoney(0d);
            }
            if(bmsDxOrder.getActualConsum() > 10000d){
                return ResultMapHelper.result(ResultCode.CODE_ORDER_ACTOAL_MAX,ResultMsg.CODE_ORDER_ACTOAL_MAX);
            }
        }

        //实付金额不能小于0
        if(bmsDxOrder.getActualConsum() <= 0d){
            bmsDxOrder.setActualConsum(0d);
        }
        bmsDxOrder.setDiscountConsum(discountConsum);
        bmsDxOrder.setBmsUserId(userId);
        bmsDxOrder.setBmsBusinessId(businessId);
        bmsDxOrder.setOrderType(orderType);
        bmsDxOrder.setOrderNo(OrderUtils.getOrderNo(businessId));
        bmsDxOrder.setVendorName(business.getVendorName());
        bmsDxOrder.setIsDelete(Constants.COMMON_FLAG_FALSE_INT);
        final int MAX_REPEAT = 5;
        //重复下单5次
        int orderNum = 0;
        while (orderNum < MAX_REPEAT){
            try {
                bmsDxOrderService.placeTheOrder(bmsDxOrder,bmsDxGroupBuy,
                        bmsUserReceCoupon,bmsBackCard,orderCommitHolder);
                break;
            }catch (Exception e){
                log.info(e.toString());
                orderNum++;
                bmsDxOrder.setOrderNo(OrderUtils.getOrderNo(businessId));
            }
        }
        if(orderNum >= MAX_REPEAT){
            return ResultMapHelper.result(ResultCode.CODE_ORDER_PLACE_FAIL,ResultMsg.CODE_ORDER_PLACE_FAIL);
        }

        if(orderType != Constants.LOCAL_LIFE_ORDER_TYPE){//本地生活订单不受30分钟限制
            bmsDxOrder.setTimingCancelTime(DateTimeUtils.addMinutes(nowTime,Constants.AUTO_CANCEL_ORDER_MINUTE));
            doOrderCancelTiming(OrderCancelTimingJob.class,bmsDxOrder.getTimingCancelTime(),bmsDxOrder);
        }
        if(bmsDxOrder.getCreateWay() == null) {
            bmsDxOrder.setCreateWay(Constants.payClientMap.get(headerData.getInteger("client")));
        }
        //真正的锁特特乐的库存
        orderSpeGroupBuyTeTeLe(bmsDxOrder,bmsThirdCodes);
        //处理订单后置逻辑
        orderHandAfterLogic(bmsDxOrder);
        orderActivityCount(bmsFullCoupon);
        //分销订单处理逻辑
        if(orderType == Constants.FX_ORDER_TYPE){
            Object shareIdObj = paramsMap.getOrDefault("shareId", null);
            if(shareIdObj == null || shareIdObj.toString().isEmpty()){
                bmsDxOrder.setShareId(null);
            }else{
                BigInteger bi = new BigInteger(String.valueOf(shareIdObj), 2);
                bmsDxOrder.setShareId(Integer.parseInt(bi.toString()));
            }
//            orderFxLogic(bmsDxOrder,paramsMap);
        }
        bmsDxOrderDao.save(bmsDxOrder);


        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("orderId",bmsDxOrder.getId());
        resultMap.put("orderNo",bmsDxOrder.getOrderNo());
        resultMap.put("newTime",bmsDxOrder.getNewTime());
        resultMap.put("timingCancelTime",bmsDxOrder.getTimingCancelTime());
        resultMap.put("bmsUserReceCoupon",bmsUserReceCoupon);
        resultMap.put("isCanrevisionPrice",isCanrevisionPrice);
        BmsCommonService.getApplicationContext().publishEvent(new OrderEvent("orderCommit",bmsDxOrder,orderCommitHolder.getUserData()));
        return ResultMapHelper.success(resultMap,"下单成功");
    }


    private void orderSpeGroupBuyTeTeLe(BmsDxOrder bmsDxOrder, List<BmsThirdCode> bmsThirdCodes) {
        if(bmsThirdCodes != null && bmsThirdCodes.size() > 0){
            for(BmsThirdCode bmsThirdCode : bmsThirdCodes){
                bmsThirdCode.setIsMatch(Constants.COMMON_FLAG_TRUE_INT);
                bmsThirdCode.setOrderId(bmsDxOrder.getId());
            }
            bmsThirdCodeService.getBaseDao().saveAll(bmsThirdCodes);
        }
    }

    public Map<String, Object> orderDetail(ParamsMap paramsMap) {
        Integer orderId = paramsMap.getInteger("orderId");
        Optional<BmsDxOrder> bmsDxOrderOptional = bmsDxOrderDao.findById(orderId);
        if(!bmsDxOrderOptional.isPresent()){
            return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_EXIST,ResultMsg.CODE_ORDER_NO_EXIST);
        }
        BmsDxOrder bmsDxOrder = bmsDxOrderOptional.get();
        //查询订单状态
        Map<String,Object> conditionMap = new LinkedHashMap<>();
        conditionMap.put("orderId",orderId);
        List<BmsDxOrderStatus> bmsDxOrderStatuses = bmsDxOrderStatusService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
        BmsDxGroupBuy bmsDxGroupBuy = bmsDxOrder.getBmsDxGroupBuy();
        if(bmsDxGroupBuy != null){
            List<BmsDxGroupBuy> bmsDxGroupBuys = new ArrayList<>();
            bmsDxGroupBuys.add(bmsDxGroupBuy);
            bmsDxGroupBuyService.postHandleGroupContent(bmsDxGroupBuys,true);
            bmsDxGroupBuyService.postHandleBusiness(bmsDxGroupBuys);
            bmsDxGroupBuyService.postHandleGroupGif(bmsDxGroupBuys);
        }
        Set<Integer> orderIds = new HashSet<>();
        orderIds.add(orderId);
        List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = bmsDxGroupBuyUseService.getBaseDao().findByGroupCodeByMySort(orderIds);
        Map<String,Object> resultMap = new LinkedHashMap<>();
        //本地生活
        Map<String, Object> localLifeInfo = getLocalLifeInfo(bmsDxOrder);
        Integer bmsBusinessId = bmsDxOrder.getBmsBusinessId();
        BmsBusiness bmsBusiness = bmsBusinessService.getBaseDao().findById(bmsBusinessId).get();
        //处理图片
        imgPrefixService.pushSpliceField(bmsBusiness,"logoUrl");
        imgPrefixService.pushSpliceField(bmsDxGroupBuy,"groupImg","detailImg","groupPhotos");
        if(bmsDxGroupBuy != null){
            imgPrefixService.pushSpliceField(bmsDxGroupBuy.getBmsBusiness(),"logoUrl");
        }
        if(CollectionUtils.isNotEmpty(bmsDxGroupBuyUses)){
            bmsDxGroupBuyUseService.postHandleQrCodeText(bmsDxGroupBuyUses);
            bmsDxOrder.setQrCodeText(bmsDxGroupBuyUses.get(0).getQrCodeText());
        }
        resultMap.put("bmsDxOrder",bmsDxOrder);
        resultMap.put("bmsOrderStatus",bmsDxOrderStatuses);
        resultMap.put("bmsDxGroupBuy",bmsDxGroupBuy);
        resultMap.put("business",bmsBusiness);
        resultMap.put("bmsDxGroupBuys",bmsDxGroupBuyUses);
        resultMap.put("localLifeInfo",localLifeInfo);


        return ResultMapHelper.success(resultMap,ResultMsg.MSG_GET_SUCCESS);
    }

    public Map<String,Object> getLocalLifeInfo(BmsDxOrder bmsDxOrder){
        Map<String, Object> localInfoMap = new HashMap<>();
        List<BmsLocalLifeGoods> resultList = new ArrayList<>();
        if(bmsDxOrder!=null&&bmsDxOrder.getOrderType() == Constants.LOCAL_LIFE_ORDER_TYPE){
            //图片处理
            imgPrefixService.pushSpliceField(bmsDxOrder,"shopList");
            Integer isTake = bmsDxOrder.getIsTake();
            Integer lifeId = bmsDxOrder.getLifeId();  //本地生活具体信息
            BmsLocalLife bmsLocalLife = bmsLocalLifeService.getBaseDao().findById(lifeId).get();
            if(isTake == 0){
                Integer shipInfo = bmsDxOrder.getShipInfo();  // 用户配送信息
                Optional<BmsUserLifeInfo> userLifeInfoOptional = bmsUserLifeInfoService.getBaseDao().findById(shipInfo);
                if(userLifeInfoOptional.isPresent()){
                    localInfoMap.put("addressInfo", userLifeInfoOptional.get());
                }
            }else{
                Map<String, Object> addressMap = new HashMap<>();
                addressMap.put("contactsName", bmsLocalLife.getContacts());
                addressMap.put("contactsPhone", bmsLocalLife.getContactsPhone());
                addressMap.put("contactsAddress", bmsLocalLife.getTakeAddress());
                localInfoMap.put("addressInfo", addressMap);
            }
            String shopList = bmsDxOrder.getShopList();
            List<BmsLocalLifeGoodsVo> bmsLocalLifeGoodsVos = JSONArray.parseArray(shopList, BmsLocalLifeGoodsVo.class);
            for(BmsLocalLifeGoodsVo vo : bmsLocalLifeGoodsVos){
                Integer goodId = vo.getGoodId();
                BmsLocalLifeGoods bmsLocalLifeGoods = bmsLocalLifeGoodsService.getBaseDao().findById(goodId).get();
                bmsLocalLifeGoods.setBuyNum(vo.getNum());
                bmsLocalLifeGoods.setTotalPrice(vo.getNum()*(bmsLocalLifeGoods.getGoodsPrice()));
                resultList.add(bmsLocalLifeGoods);
            }
            localInfoMap.put("isTake", isTake);
            localInfoMap.put("shopList", resultList);
            localInfoMap.put("remark", bmsDxOrder.getRemark());
            localInfoMap.put("deliveryRules", bmsLocalLife.getDeliveryRules());

        }
        return localInfoMap;
    }

    @Transactional(rollbackFor = Exception.class)
    public Map<String,Object> refundOrder_v3(ParamsMap paramsMap) throws Exception {
        Map<String,Object> handleMap = this.userRefundOrderOrder_v3(paramsMap);
        if(!ResultCode.CODE_NORMAL.equals(handleMap.get("status").toString())){
            return handleMap;
        }
        BmsDxOrder bmsDxOrder = (BmsDxOrder) handleMap.get("data");
        Map<String,Object> userDataMap = (Map<String, Object>) handleMap.get("userData");
        if(bmsDxOrder.getCreateWay() == null){
            bmsDxOrder.setCreateWay(Constants.ANDROID_CLIENT);
        }
        /*boolean isRefund = false;
        //退款金额
        Double orderRefund = Double.parseDouble(userDataMap.get("refundTotal").toString());
        if(bmsDxOrder.getPayWay() == Constants.ALI_PAY) {
            isRefund = aliPayService.refundMoney(bmsDxOrder,orderRefund,aliPayController.getAlipayClient());
        }else if(bmsDxOrder.getPayWay() == Constants.WX_PAY){
            WxPayBean wxPayConfig = wxPayService.getApiConfigByChannel(WxPayBeanFactory.MIN_APP_CHANNEL);
            isRefund = wxPayService.refundMoney(bmsDxOrder, orderRefund, wxPayConfig);
        }
        if(!isRefund){
            throw new Exception("退款失败");
        }*/
        List<BmsDxGroupBuyUse> groupBuyUseList = (List<BmsDxGroupBuyUse>) userDataMap.get("bmsDxGroupBuyUses");
        //存储处理时间
        Date nowTime = new Date();
        /*for(BmsDxGroupBuyUse bmsDxGroupBuyUse : groupBuyUseList){
            bmsDxGroupBuyUse.setAcceptTime(nowTime);
            bmsDxGroupBuyUse.setRefundTime(nowTime);
        }*/
        //userDataMap.put("refundTime", DateTimeUtils.converDateToString(groupBuyUseList.get(0).getRefundTime(),DateTimeUtils.DATE_PATTERN_DAY_05));
        userDataMap.put("refundTime",nowTime);
        userDataMap.put("refundNum",groupBuyUseList.size());
        //保存状态和时间
        bmsDxGroupBuyUseService.getBaseDao().saveAll(groupBuyUseList);
        //发送消息
        paramsMap.clear();
        paramsMap.put("userIdentify",bmsDxOrder.getBmsUserId().toString());
        paramsMap.put("orderId",bmsDxOrder.getId());
        paramsMap.put("groupBuyUseId",groupBuyUseList.get(0).getId());
        BmsCommonService.getApplicationContext().publishEvent(new OrderEvent("orderRefund_ing",bmsDxOrder,userDataMap));
        return ResultMapHelper.success(userDataMap, ResultMsg.CODE_ORDER_RUFUND_SUCCESS);
    }

    /**
     * 关于团购的退款做一个说明：
     *
     * 假设某团购有效期到7月10日（含）
     *
     * 支持过期退、随时退=7月10日前后随时都可以通过退款按钮发起退款
     * 支持过期退、不支持随时退=7月10日后可以通过退款按钮发起退款，7月10日（含）前不行
     * 不支持过期退、支持随时退=7月10日（含）前可以通过退款按钮发起退款，7月10日后不行
     * 不支持过期退、不支持随时退=都不可退
     *
     * 在不能退款的情况，点击退款按钮弹toast提示：“该团购暂不支持退款”
     * @param paramsMap
     * @return
     * @throws Exception
     */
    private Map<String, Object> userRefundOrderOrder_v3(ParamsMap paramsMap) throws Exception {
        Date nowTime = new Date();
        Map<String,Object> userDataMap = new HashMap<>();
        Integer userId = Integer.parseInt(paramsMap.get("userIdentify").toString());
        Integer orderId = Integer.parseInt(paramsMap.get("orderId").toString());
        Map<String,Object> checkMap = checkOrderIsTrue(userId,orderId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        BmsDxOrder bmsDxOrder = (BmsDxOrder) checkMap.get("data");
        BmsDxGroupBuy bmsDxGroupBuy = bmsDxOrder.getBmsDxGroupBuy();
        boolean isRefundAnyTime = false;
        if(bmsDxGroupBuy.getIsRefundAnyTime() != null && bmsDxGroupBuy.getIsRefundAnyTime().equals(Constants.COMMON_FLAG_TRUE_INT)){
            isRefundAnyTime = true;
        }
        boolean isOverdueRefund = false;
        if(bmsDxGroupBuy.getIsOverdueRefund() != null && bmsDxGroupBuy.getIsOverdueRefund().equals(Constants.COMMON_FLAG_TRUE_INT)){
            isOverdueRefund = true;
        }
        //不支持随时退，也不支持过期退
        if(!isRefundAnyTime && !isOverdueRefund){
            return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_SUPPORT_REFUND, ResultMsg.CODE_ORDER_NO_REFUND_ANY);
        }
        //判断团购过没过期
        if(bmsDxGroupBuy.getExpireTime() != null) {
            if (DateTimeUtils.match(nowTime, DateTimeUtils.addDay(bmsDxGroupBuy.getExpireTime(),1), DateTimeUtils.MATCH_MODEL_GTE)) {
                //过期
                if(!isOverdueRefund){
                    return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_SUPPORT_REFUND, ResultMsg.CODE_ORDER_NO_REFUND_ANY);
                }
            } else {
                //没过期
                if(!isRefundAnyTime){
                    return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_SUPPORT_REFUND, ResultMsg.CODE_ORDER_NO_REFUND_ANY);
                }
            }
        }
        List<String> groupBuyIds;
        if(paramsMap.get("groupBuyUseIds") instanceof String){
            groupBuyIds = (List<String>) JSON.parse(paramsMap.get("groupBuyUseIds").toString());
        }else {
            groupBuyIds = (List) paramsMap.get("groupBuyUseIds");
        }
        Set<Integer> groupBuyUseIds = new HashSet<>();
        for(String groupById : groupBuyIds){
            groupBuyUseIds.add(Integer.parseInt(groupById));
        }
        //查看团购券是否已经是已退款状态
        List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = bmsDxGroupBuyUseService.getBaseDao().findByIdIn(groupBuyUseIds);
        if(!(bmsDxGroupBuyUses != null && bmsDxGroupBuyUses.size() > 0)) {
            return ResultMapHelper.result(ResultCode.CODE_ORDER_GROUP_NO_EXIST, ResultMsg.CODE_ORDER_GROUP_NO_EXIST);
        }
        for(BmsDxGroupBuyUse bmsDxGroupBuyUse : bmsDxGroupBuyUses){
            if(bmsDxGroupBuyUse.getStatus() == Constants.GROUP_REFUND_COMPLETE){
                return ResultMapHelper.result(ResultCode.CODE_ORDER_GROUP_AL_REFUND,ResultMsg.CODE_ORDER_GROUP_AL_REFUND);
            }
            if(bmsDxGroupBuyUse.getStatus() == Constants.GROUP_ALREADY_USE){
                return ResultMapHelper.result(ResultCode.CODE_ORDER_GROUP_AL_USE,ResultMsg.CODE_ORDER_GROUP_AL_USE);
            }
            if(bmsDxGroupBuyUse.getIsRefund() == Constants.COMMON_FLAG_TRUE_INT){
                return ResultMapHelper.result(ResultCode.CODE_ORDER_ALREAD_REFUND,ResultMsg.MSG_ORDER_ALREAD_REFUND);
            }
            if(bmsDxGroupBuyUse.getOrderId() != orderId.intValue()){
                return ResultMapHelper.result(ResultCode.CODE_ORDER_GROUP_USE_NO_MATCH_ORDER,ResultMsg.CODE_ORDER_GROUP_USE_NO_MATCH_ORDER);
            }
        }

        if(bmsDxOrder.getOrderType() == Constants.ONLINE_ORDER_TYPE
                || bmsDxOrder.getOrderType() == Constants.COUPONS_ORDER_TYPE){
            return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_SUPPORT_REFUND,ResultMsg.CODE_ORDER_NO_SUPPORT_REFUND);
        }
        Double total = 0d;
        Double useBackMoney = 0d;
        for(BmsDxGroupBuyUse bmsDxGroupBuyUse : bmsDxGroupBuyUses){
            bmsDxGroupBuyUse.setCommitTime(nowTime);
            //发起退款
            bmsDxGroupBuyUse.setIsRefund(Constants.COMMON_FLAG_TRUE_INT);
            bmsDxGroupBuyUse.setRefundResult(Constants.REFUND_IMG);
            bmsDxGroupBuyUse.setAuditStatus(Constants.SYS_AUDIT_IMG);
            bmsDxGroupBuyUse.setAcceptStatus(Constants.COMMON_FLAG_FALSE_INT);
            bmsDxGroupBuyUse.setRefundStatus(Constants.COMMON_FLAG_FALSE_INT);
            total = ArithUtil.add(total,bmsDxGroupBuyUse.getGbuyActualConsum());
            /*if(bmsDxGroupBuyUse.getBackCacdMoney() != null){
                useBackMoney = ArithUtil.add(useBackMoney,bmsDxGroupBuyUse.getBackCacdMoney());
            }*/
        }
        userDataMap.put("bmsDxGroupBuyUses",bmsDxGroupBuyUses);
        Set useStatus = new HashSet<>(Arrays.asList(new Integer[]{Constants.GROUP_ALREADY_USE,Constants.GROUP_REFUND_COMPLETE}));
        Integer num = bmsDxGroupBuyUseService.getBaseDao().countOrderStatuNum(orderId,useStatus);
        //全部退完
        if((num + bmsDxGroupBuyUses.size()) == bmsDxOrder.getGroupBuyNum().intValue()){
            bmsDxOrderStatusService.deleteAllRefundStatus(bmsDxOrder.getId(),Constants.ALREADY_USE);
        }
        //添加一条退款中的记录
        bmsDxOrderStatusService.addOrderStatus(bmsDxOrder,Constants.REFUND_ING);
        //删除已退款标识
        bmsDxOrderStatusService.deleteAllRefundStatus(bmsDxOrder.getId(),Constants.REFUND_COMPLETE);

        //查看能够用的是不是全部退完

        //查看之前是否已经有退款中和已退款的订单
        /*List<BmsDxOrderStatus> bmsDxOrderStatusList = new LinkedList<>();
        Set<Integer> statuses = new HashSet<>();
        statuses.add(Constants.REFUND_ING);
        statuses.add(Constants.REFUND_COMPLETE);
        List<BmsDxOrderStatus> bmsDxOrderStatuses = bmsDxOrderStatusService.
                getBaseDao().findByOrderIdAndStatusIn(orderId,statuses);
        //删除已退款的记录，保留退款中的记录
        if(bmsDxOrderStatuses != null && bmsDxOrderStatuses.size() > 0){
            for(BmsDxOrderStatus bmsDxOrderStatus : bmsDxOrderStatuses){
                if(bmsDxOrderStatus.getStatus() == Constants.REFUND_COMPLETE){
                    bmsDxOrderStatusService.getBaseDao().delete(bmsDxOrderStatus);
                }else {
                    if(bmsDxOrderStatusList.size() < 1) {
                        bmsDxOrderStatusList.add(bmsDxOrderStatus);
                    }else {
                        bmsDxOrderStatusService.getBaseDao().delete(bmsDxOrderStatus);
                    }
                }
            }
        }
        if(bmsDxOrderStatusList.size() == Constants.COMMON_FLAG_FALSE_INT) {
            //插入一条退款中记录
            BmsDxOrderStatus bmsDxOrderStatus = new BmsDxOrderStatus();
            bmsDxOrderStatus.setOrderId(bmsDxOrder.getId());
            bmsDxOrderStatus.setOrderType(bmsDxOrder.getOrderType());
            bmsDxOrderStatus.setUserId(bmsDxOrder.getBmsUserId());
            bmsDxOrderStatus.setStatus(Constants.REFUND_ING);
            bmsDxOrderStatus.setNewTime(bmsDxOrder.getNewTime());
            bmsDxOrderStatus.setBusinessId(bmsDxOrder.getBmsBusinessId());
            bmsDxOrderStatus.setPayTime(bmsDxOrder.getPayTime());
            bmsDxOrderStatusService.getBaseDao().save(bmsDxOrderStatus);
        }*/
        //查看是否全额退款
        /*int alreadRufund = bmsDxGroupBuyUseService.getBaseDao().countOrderStatuNum(orderId,Constants.GROUP_REFUND_COMPLETE);
        if(alreadRufund == bmsDxOrder.getGroupBuyNum()) {
            bmsDxOrderStatus = bmsDxOrderStatusService.
                    getBaseDao().findByOrderIdAndStatus(orderId, Constants.ALREADY_USE);
            bmsDxOrderStatusService.getBaseDao().delete(bmsDxOrderStatus);
        }else if(alreadRufund < bmsDxOrder.getGroupBuyNum()){
            //查看没用的记录
            Map<String,Object> conditionMap = new HashMap<>();
            conditionMap.put("orderId",orderId);
            conditionMap.put("status",Constants.GROUP_ALREADY_USE);
            Integer useNum = (int)bmsDxGroupBuyUseService.getBaseDao().count(new SpecificationUtils(conditionMap));
            if((useNum + alreadRufund) == bmsDxOrder.getGroupBuyNum()){
                //代表订单完成
                bmsDxOrderStatus = bmsDxOrderStatusService.
                        getBaseDao().findByOrderIdAndStatus(orderId, Constants.ALREADY_USE);
                bmsDxOrderStatus.setStatus(Constants.PAY_COMPLETE);
                bmsDxOrderStatusService.getBaseDao().save(bmsDxOrderStatus);
            }
        }*/
        //将退款的张数退回至团购券
        /*if(bmsDxGroupBuy.getSellInventory() != null) {
            bmsDxGroupBuy.setSellInventory(bmsDxGroupBuy.getSellInventory() + bmsDxGroupBuyUses.size());
            bmsDxGroupBuyService.getBaseDao().save(bmsDxGroupBuy);
        }
        //如果是特特乐团购，库存回归
        if(bmsDxGroupBuy.getGroupType() != null && bmsDxGroupBuy.getGroupType() == Constants.GROUP_TYPE_TETE){
            Set<String> codes = bmsDxGroupBuyUses.stream().map(BmsDxGroupBuyUse::getGroupBuyCode).collect(Collectors.toSet());
            bmsThirdCodeService.stockReturn(codes,orderId);
        }
        //如果有满减券的情况调回未使用
        if(bmsDxOrder.getFullCouponId() != null){
            //是否退完
            if(alreadRufund == bmsDxOrder.getGroupBuyNum()) {
                bmsUserReceCouponService.updateFullCouponIsUse(bmsDxOrder.getFullCouponId());
                bmsUserReceCouponService.removeFullCouponUseNum(bmsDxOrder.getFullCouponId());
            }
        }
        if(bmsDxOrder.getBackCardId() != null){
            //将返现的卡的钱回至返现卡
            bmsBackCardService.addMoney(bmsDxOrder.getBackCardId(),useBackMoney);
        }*/
        userDataMap.put("refundTotal",total);
        userDataMap.put("groupBuyId",bmsDxGroupBuy.getId());
        return ResultMapHelper.success(bmsDxOrder,userDataMap);
    }

    @GlobalTransactional(rollbackFor = Exception.class)
    public void orderRefundHandle(BmsDxOrder bmsDxOrder,
                                  BmsDxOrderStatus bmsDxOrderStatus,
                                  BmsDxGroupBuy bmsDxGroupBuy,
                                  List<BmsDxGroupBuyUse> bmsDxGroupBuyUses) throws Exception {
        Integer orderId = bmsDxOrderStatus.getOrderId();
        Date nowTime = new Date();
        Integer timestamp = DateTimeUtils.converDateToInterger(nowTime);
        System.out.println("当前时间：" + nowTime.getTime());
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("isRefund",Constants.COMMON_FLAG_TRUE_INT);
        conditionMap.put("refundResult",Constants.REFUND_IMG);
        conditionMap.put("orderId",orderId);
        if(bmsDxGroupBuyUses != null && bmsDxGroupBuyUses.size() > 0){
            Double total = 0d;
            Double useBackMoney = 0d;
            Map<String,Object> userDataMap = new HashMap<>();
            List<BmsDxGroupBuyUse> buyUses = new LinkedList<>();
            List<BmsDxGroupBuyUse> buyRefundFails = new LinkedList<>();
            for(BmsDxGroupBuyUse bmsDxGroupBuyUse : bmsDxGroupBuyUses){
                Integer commitTime = DateTimeUtils.converDateToInterger(DateTimeUtils.addMinutes(bmsDxGroupBuyUse.getCommitTime(),1));
                if(BmsCommonService.checkRunProfile(BmsCommonService.RUN_PRO)){
                    commitTime = DateTimeUtils.converDateToInterger(DateTimeUtils.addDay(bmsDxGroupBuyUse.getCommitTime(),1));
                }
                if(commitTime <= timestamp){
                    if(bmsDxGroupBuyUse.getStatus() == Constants.GROUP_ALREADY_USE){
                        buyRefundFails.add(bmsDxGroupBuyUse);
                    } else {
                        buyUses.add(bmsDxGroupBuyUse);
                    }
                }
            }

            if(buyRefundFails != null && buyRefundFails.size() > 0){
                Double refundFailTotal = 0d;
                for(BmsDxGroupBuyUse bmsDxGroupBuyUse : buyRefundFails){
                    bmsDxGroupBuyUse.setAuditStatus(Constants.SYS_AUDIT_NOT_CAN);
                    bmsDxGroupBuyUse.setAuditTime(nowTime);
                    bmsDxGroupBuyUse.setIsRefund(Constants.COMMON_FLAG_FALSE_INT);
                    bmsDxGroupBuyUse.setRefundResult(Constants.REFUND_FAIL);
                    refundFailTotal = ArithUtil.add(refundFailTotal,bmsDxGroupBuyUse.getGbuyActualConsum());
                }
                bmsDxGroupBuyUseService.getBaseDao().saveAll(buyRefundFails);
                int refundNum = bmsDxGroupBuyUseService.countRefundNum(orderId);
                if(refundNum > 0){
                    bmsDxOrderStatusService.addOrderStatus(bmsDxOrder,Constants.REFUND_COMPLETE);
                }else {
                    bmsDxOrderStatusService.deleteAllRefundStatus(orderId,Constants.REFUND_COMPLETE);
                }
                int refundIngNum = bmsDxGroupBuyUseService.countRefundIngNum(orderId);
                if(refundIngNum > 0){
                    bmsDxOrderStatusService.deleteAllRefundStatus(orderId,Constants.REFUND_COMPLETE);
                    bmsDxOrderStatusService.addOrderStatus(bmsDxOrder,Constants.REFUND_ING);
                }else {
                    bmsDxOrderStatusService.deleteAllRefundStatus(orderId,Constants.REFUND_ING);
                }
                //发送推送消息
                userDataMap.put("refundTotal",refundFailTotal);
                userDataMap.put("groupBuyId",bmsDxGroupBuy.getId());
                userDataMap.put("refundTime",nowTime);
                userDataMap.put("refundNum",buyRefundFails.size());
                userDataMap.put("bmsDxGroupBuyUses",buyRefundFails);
                //查询退款明细
                ParamsMap paramsMap = new ParamsMap();
                paramsMap.put("userIdentify",bmsDxOrder.getBmsUserId().toString());
                paramsMap.put("orderId",bmsDxOrder.getId());
                paramsMap.put("groupBuyUseId",buyRefundFails.get(0).getId());
                BmsCommonService.getApplicationContext().publishEvent(new OrderEvent("orderRefund_fail",bmsDxOrder,userDataMap));
            }
            if(!(buyUses != null && buyUses.size() > 0)){
                return;
            }
            for(BmsDxGroupBuyUse bmsDxGroupBuyUse : buyUses){
                bmsDxGroupBuyUse.setStatus(Constants.GROUP_REFUND_COMPLETE);
                bmsDxGroupBuyUse.setIsRefund(Constants.COMMON_FLAG_FALSE_INT);
                bmsDxGroupBuyUse.setRefundResult(Constants.REFUND_SUCCESS);
                bmsDxGroupBuyUse.setAuditStatus(Constants.SYS_AUDIT_CAN);
                bmsDxGroupBuyUse.setAuditTime(nowTime);
                bmsDxGroupBuyUse.setAcceptStatus(Constants.COMMON_FLAG_TRUE_INT);
                bmsDxGroupBuyUse.setAcceptTime(nowTime);
                bmsDxGroupBuyUse.setRefundStatus(Constants.COMMON_FLAG_TRUE_INT);
                bmsDxGroupBuyUse.setRefundTime(nowTime);
                total = ArithUtil.add(total,bmsDxGroupBuyUse.getGbuyActualConsum());
                if(bmsDxGroupBuyUse.getBackCacdMoney() != null){
                    useBackMoney = ArithUtil.add(useBackMoney,bmsDxGroupBuyUse.getBackCacdMoney());
                }
            }
            bmsDxGroupBuyUseService.getBaseDao().saveAll(buyUses);
            int alreadRufund = bmsDxGroupBuyUseService.getBaseDao().countOrderStatuNum(orderId, Constants.GROUP_REFUND_COMPLETE);
            if (alreadRufund == bmsDxOrder.getGroupBuyNum()) {
                //将可使用状态删除
                /*bmsDxOrderStatus = bmsDxOrderStatusService.
                        getBaseDao().findByOrderIdAndStatus(orderId, Constants.ALREADY_USE);
                bmsDxOrderStatusService.getBaseDao().delete(bmsDxOrderStatus);*/
                bmsDxOrderStatusService.deleteAllRefundStatus(orderId,Constants.ALREADY_USE);
                //将退款中设置成已退款
                bmsDxOrderStatus = bmsDxOrderStatusService.
                        getBaseDao().findByOrderIdAndStatus(orderId, Constants.REFUND_ING);
                bmsDxOrderStatus.setStatus(Constants.REFUND_COMPLETE);
                bmsDxOrderStatusService.getBaseDao().save(bmsDxOrderStatus);
            } else if (alreadRufund < bmsDxOrder.getGroupBuyNum()) {
                Integer useNum = bmsDxGroupBuyUseService.getBaseDao().countOrderStatuNum(orderId,Constants.GROUP_ALREADY_USE);
                if((useNum + alreadRufund) == bmsDxOrder.getGroupBuyNum()){
                    //代表订单完成
                    /*bmsDxOrderStatus = bmsDxOrderStatusService.
                            getBaseDao().findByOrderIdAndStatus(orderId, Constants.ALREADY_USE);
                    bmsDxOrderStatus.setStatus(Constants.PAY_COMPLETE);
                    bmsDxOrderStatusService.getBaseDao().save(bmsDxOrderStatus);*/
                    bmsDxOrderStatusService.addOrderStatus(bmsDxOrder,Constants.PAY_COMPLETE);
                    bmsDxOrderStatusService.deleteAllRefundStatus(bmsDxOrder.getId(),Constants.REFUND_ING);
                }
                int refundIngNum = bmsDxGroupBuyUseService.countRefundIngNum(orderId);
                if(refundIngNum > 0){
                    bmsDxOrderStatusService.deleteAllRefundStatus(orderId,Constants.REFUND_COMPLETE);
                    bmsDxOrderStatusService.addOrderStatus(bmsDxOrder,Constants.REFUND_ING);
                }else {
                    //查看是否有退款完成记录
                    int refundNum = bmsDxGroupBuyUseService.countRefundNum(orderId);
                    if (refundNum > 0) {
                        bmsDxOrderStatusService.deleteAllRefundStatus(orderId,Constants.REFUND_ING);
                        bmsDxOrderStatusService.addOrderStatus(bmsDxOrder, Constants.REFUND_COMPLETE);
                    }
                }
            }
            //将退款的张数退回至团购券
            if(bmsDxGroupBuy.getSellInventory() != null) {
                bmsDxGroupBuy.setSellInventory(bmsDxGroupBuy.getSellInventory() + bmsDxGroupBuyUses.size());
                bmsDxGroupBuyService.getBaseDao().save(bmsDxGroupBuy);
            }
            //如果是特特乐团购，库存回归
            if(bmsDxGroupBuy.getGroupType() != null && bmsDxGroupBuy.getGroupType() == Constants.GROUP_TYPE_TETE){
                Set<String> codes = bmsDxGroupBuyUses.stream().map(BmsDxGroupBuyUse::getGroupBuyCode).collect(Collectors.toSet());
                bmsThirdCodeService.stockReturn(codes,orderId);
            }
            //如果有满减券的情况调回未使用
            if(bmsDxOrder.getFullCouponId() != null){
                //是否退完
                if(alreadRufund == bmsDxOrder.getGroupBuyNum()) {
                    bmsUserReceCouponService.updateFullCouponIsUse(bmsDxOrder.getFullCouponId());
                    bmsUserReceCouponService.removeFullCouponUseNum(bmsDxOrder.getFullCouponId());
                }
            }
            if(bmsDxOrder.getBackCardId() != null){
                //将返现的卡的钱回至返现卡
                bmsBackCardService.addMoney(bmsDxOrder.getBackCardId(),useBackMoney);
            }

            //TODO 分销钱包退款
            Integer refundNum = bmsDxGroupBuyUses.size();
            Double useFxMoney = bmsDxOrder.getUseFxMoney() == null?0:bmsDxOrder.getUseFxMoney();
            Double unitFxMoney = useFxMoney/bmsDxOrder.getGroupBuyNum();
            if(bmsDxOrder.getOrderType() == Constants.FX_ORDER_TYPE){
                VerifyCodeDto verifyCodeDto = new VerifyCodeDto();
                verifyCodeDto.setOrderId(bmsDxOrder.getId());
                verifyCodeDto.setUserId(bmsDxOrder.getBmsUserId());
                Double shareComm = refundNum * bmsDxGroupBuy.getAcrossCommision();
                Double buyComm = refundNum * bmsDxGroupBuy.getCommision();
                verifyCodeDto.setUseFxMoney(BigDecimal.valueOf(unitFxMoney * refundNum));
                verifyCodeDto.setBuyComm(BigDecimal.valueOf(buyComm));
                verifyCodeDto.setShareComm(BigDecimal.valueOf(shareComm));
                if(bmsDxGroupBuy.getIsBusinessConsume() == Constants.COMMON_FLAG_TRUE_INT){
                    Map<String, Object> refundMap = fxCenterService.fxOrderRefund(verifyCodeDto);
                }
            }else{
                if(bmsDxOrder.getUseFxMoney() != null){
                    RefundDto refundDto = new RefundDto();
                    refundDto.setOrderId(bmsDxOrder.getId());
                    refundDto.setUserId(bmsDxOrder.getBmsUserId());
                    refundDto.setUseFxMoney(BigDecimal.valueOf(unitFxMoney * refundNum));
                    if(bmsDxGroupBuy.getIsBusinessConsume() == Constants.COMMON_FLAG_TRUE_INT){
                        fxCenterService.otherOrderRefund(refundDto);
                    }
                }
            }

            //TODO 开始进行退款
            boolean isRefund = false;
            //退款金额
            Double orderRefund = total;
            if(bmsDxOrder.getPayWay() == Constants.ALI_PAY) {
                isRefund = aliPayService.refundMoney(bmsDxOrder,orderRefund,
                        aliPayService.getAlipayClient(DateTimeUtils.converDateToInterger(bmsDxOrder.getNewTime())));
            }else if(bmsDxOrder.getPayWay() == Constants.WX_PAY){
                WxPayBean wxPayConfig = wxPayService.getApiConfigByChannel(WxPayBeanFactory.MIN_APP_CHANNEL);
                isRefund = wxPayService.refundMoney(bmsDxOrder, orderRefund,buyUses,wxPayConfig);
            }
            if(!isRefund){
                throw new Exception("订单id:" + bmsDxOrder.getId() + "-->退款失败");
            }
            log.info("定时退款结束，退款订单id : " + bmsDxOrder.getId());
            try {
                userDataMap.put("refundTotal",total);
                userDataMap.put("groupBuyId",bmsDxGroupBuy.getId());
                userDataMap.put("refundTime",nowTime);
                userDataMap.put("refundNum",buyUses.size());
                userDataMap.put("bmsDxGroupBuyUses",buyUses);
                ParamsMap paramsMap = new ParamsMap();
                paramsMap.put("userIdentify",bmsDxOrder.getBmsUserId().toString());
                paramsMap.put("orderId",bmsDxOrder.getId());
                paramsMap.put("groupBuyUseId",buyUses.get(0).getId());
                BmsCommonService.getApplicationContext().publishEvent(new OrderEvent("orderRefund_success",bmsDxOrder,userDataMap));
            }catch (Exception e){
                log.error("finally refundError:",e);
            }
        }
    }

    public Map<String, Object> checkOrderIsExist(Integer orderId) {
        BmsDxOrder bmsDxOrder = bmsDxOrderDao.findByIdAndIsDelete(orderId,Constants.COMMON_FLAG_FALSE_INT);
        if(bmsDxOrder != null){
            return ResultMapHelper.success(null,ResultMsg.HAND_SUCCESS);
        }
        return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_EXIST,ResultMsg.CODE_ORDER_NO_EXIST);
    }

    public Map<String, Object> getRefundOrderDetail_v3(ParamsMap paramsMap) {
        Integer userId = paramsMap.getInteger("userIdentify");
        Integer orderId = paramsMap.getInteger("orderId");
        Integer groupBuyUseId = Integer.parseInt(paramsMap.get("groupBuyUseId").toString());
        Integer newId = paramsMap.getInteger("newId");
        Map<String,Object> checkMap = checkOrderIsTrue(userId,orderId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        BmsDxOrder bmsDxOrder = (BmsDxOrder) checkMap.get("data");
        OrderRefundDetailRpDto orderRefundDetailRpDto = new OrderRefundDetailRpDto();
        if(newId == null) {
            Optional<BmsDxGroupBuyUse> bmsDxGroupBuyUse = bmsDxGroupBuyUseService.getBaseDao().findById(groupBuyUseId);
            if (bmsDxGroupBuyUse.isPresent()) {
                if (bmsDxGroupBuyUse.get().getOrderId().intValue() != bmsDxOrder.getId().intValue()) {
                    return ResultMapHelper.result(ResultCode.CODE_ORDER_GROUP_USE_NO_MATCH_ORDER, ResultMsg.CODE_ORDER_GROUP_USE_NO_MATCH_ORDER);
                }
                BeanUtils.copyProperties(bmsDxGroupBuyUse.get(), orderRefundDetailRpDto);
                orderRefundDetailRpDto.setRefundMoney(bmsDxGroupBuyUse.get().getGbuyActualConsum());
                orderRefundDetailRpDto.setPayWay(bmsDxOrder.getPayWay());
            }
        }else {
            Optional<BmsDxNews> bmsDxNewsOptional = bmsDxNewsService.getBaseDao().findById(newId);
            if(bmsDxNewsOptional.isPresent()) {
                BmsDxNews bmsDxNews = bmsDxNewsOptional.get();
                if (bmsDxNews.getBmsGroupBuyUseId() != null) {
                    Optional<BmsDxGroupBuyUse> bmsDxGroupBuyUse = bmsDxGroupBuyUseService.getBaseDao().findById(bmsDxNews.getBmsGroupBuyUseId());
                    if(bmsDxGroupBuyUse.isPresent()){
                        BmsDxGroupBuyUse bu = bmsDxGroupBuyUse.get();
                        Map<String, Object> conditionMap = new HashMap<>();
                        conditionMap.put("orderId", bu.getOrderId());
                        conditionMap.put("refundResult", bu.getRefundResult());
                        conditionMap.put("commitTime", bu.getCommitTime());
                        List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = bmsDxGroupBuyUseService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
                        if (bmsDxGroupBuyUse != null && bmsDxGroupBuyUses.size() > 0) {
                            BeanUtils.copyProperties(bmsDxGroupBuyUses.get(0), orderRefundDetailRpDto);
                            Double refundTotal = 0d;
                            for (BmsDxGroupBuyUse groupBuyUse : bmsDxGroupBuyUses) {
                                refundTotal = ArithUtil.add(refundTotal, groupBuyUse.getGbuyActualConsum());
                            }
                            orderRefundDetailRpDto.setRefundMoney(refundTotal);
                            orderRefundDetailRpDto.setPayWay(bmsDxOrder.getPayWay());
                        }
                    }
                }
            }
        }
        if(bmsDxOrder.getPayWay() == Constants.ALI_PAY){
            orderRefundDetailRpDto.setSerialNumber(bmsDxOrder.getPayNo());
        }else if(bmsDxOrder.getPayWay() == Constants.WX_PAY){
            orderRefundDetailRpDto.setSerialNumber(bmsDxOrder.getTransactionId());
        }
        return ResultMapHelper.success(orderRefundDetailRpDto,ResultMsg.MSG_GET_SUCCESS);
    }

    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> refundLocalLifeOrder(Integer orderId) throws Exception {
        BmsDxOrder bmsDxOrder = bmsDxOrderDao.findByIdAndIsDelete(orderId,Constants.COMMON_FLAG_FALSE_INT);
        if(bmsDxOrder == null){
            return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_EXIST,ResultMsg.CODE_ORDER_NO_EXIST);
        }
        BmsDxOrderStatus bmsDxOrderStatus = bmsDxOrderStatusService.getBaseDao().
                findByOrderIdAndStatus(orderId,Constants.WAIT_GET);
        if(bmsDxOrderStatus == null){
            return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_PAY,ResultMsg.CODE_ORDER_NO_PAY);
        }
        //业务逻辑
        bmsDxOrderStatus.setStatus(Constants.REFUND_COMPLETE);
        bmsDxOrderStatusService.getBaseDao().save(bmsDxOrderStatus);
        Double orderRefund = bmsDxOrder.getActualConsum();
        boolean isRefund = false;
        if(bmsDxOrder.getPayWay() == Constants.ALI_PAY) {
            isRefund = aliPayService.refundMoney(bmsDxOrder,orderRefund,
                    aliPayService.getAlipayClient(DateTimeUtils.converDateToInterger(bmsDxOrder.getNewTime())));
        }else if(bmsDxOrder.getPayWay() == Constants.WX_PAY){
            WxPayBean wxPayConfig = wxPayService.getApiConfigByChannel(WxPayBeanFactory.MIN_APP_CHANNEL);
            isRefund = wxPayService.refundMoney(bmsDxOrder, orderRefund, wxPayConfig);
        }
        if(!isRefund){
            throw new Exception("退款失败");
        }
        if(bmsDxOrder.getUseFxMoney() != null && bmsDxOrder.getUseFxMoney() > 0){
//            Map<String, Object> conditionMap = new HashMap<>();
//            conditionMap.put("userId",bmsDxOrder.getBmsUserId());
//            List<BmsFxFirst> bmsFxFirstList = bmsFxFirstDao.findAll(new SpecificationUtils(conditionMap));
//            List<BmsFxSecond> bmsFxSecondList = bmsFxSecondDao.findAll(new SpecificationUtils(conditionMap));
//            if(CollectionUtils.isNotEmpty(bmsFxFirstList) && bmsFxFirstList.size()>0){
//                BmsFxFirst bmsFxFirst = bmsFxFirstList.get(0);
//                bmsFxFirst.setBalance(bmsFxFirst.getBalance().add(new BigDecimal(bmsDxOrder.getUseFxMoney())));
//                bmsFxFirstDao.save(bmsFxFirst);
//            }else if(CollectionUtils.isNotEmpty(bmsFxSecondList) && bmsFxSecondList.size()>0){
//                BmsFxSecond bmsFxSecond = bmsFxSecondList.get(0);
//                bmsFxSecond.setBalance(bmsFxSecond.getBalance().add(new BigDecimal(bmsDxOrder.getUseFxMoney())));
//                bmsFxSecondDao.save(bmsFxSecond);
//            }
            RefundDto refundDto = new RefundDto();
            refundDto.setUserId(bmsDxOrder.getBmsUserId());
            refundDto.setOrderId(bmsDxOrder.getId());
            refundDto.setUseFxMoney(BigDecimal.valueOf(bmsDxOrder.getUseFxMoney()));
            fxCenterService.otherOrderRefund(refundDto);
        }

        return ResultMapHelper.success(null,"退款成功");
    }

    public Double findUserBuyMaskNum(Integer userId) {
        Integer num = bmsDxOrderDao.countUserBuyMask(userId);
        if(num == null){
            return null;
        }
        return Double.parseDouble(bmsDxOrderDao.countUserBuyMask(userId).toString());
    }

    public void transMoneyToCoustomer(BmsDxOrder bmsDxOrder) {
        try {
            if(StringUtils.isNotBlank(bmsDxOrder.getPayNo()) && bmsDxOrder.getPayNo().indexOf("test") != - 1){
                return;
            }
            List<BmsCustomer> bmsCustomers = bmsCustomerService.getOnlineCoustomer();
            if(bmsCustomers.size() > 0) {
                BmsCustomer bmsCustomer = bmsCustomers.get(0);
                wxPayService.transfersMoneyToCustomerByWxPay(bmsDxOrder,bmsCustomer.getOpenid(),bmsCustomer.getUserName());
                /*if (bmsDxOrder.getPayWay() == Constants.ALI_PAY) {
                    aliPayService.transfersMoneyToCustomerByAliPay(bmsDxOrder,bmsCustomer.getUid());
                } else if (bmsDxOrder.getPayWay() == Constants.WX_PAY) {
                    wxPayService.transfersMoneyToCustomerByWxPay(bmsDxOrder,bmsCustomer.getOpenid(),bmsCustomer.getUserName());
                }*/
            }
        }catch (Exception e){
            log.error("transfer error：",e);
        }

    }

    //@GlobalTransactional(rollbackFor = Exception.class)
    public void test() {
        //找出所有退款中的订单
        BmsDxOrder bmsDxOrder = bmsDxOrderService.getBaseDao().findById(88).get();
        bmsDxOrder.setPayNo("789");
        bmsDxOrderService.getBaseDao().save(bmsDxOrder);
        fxCenterService.test();
        int i = 7/0;
    }

    public void orderRufund() {
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("status",Constants.REFUND_ING);
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        List<BmsDxOrderStatus> bmsDxOrderStatuses = bmsDxOrderStatusService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
        if(bmsDxOrderStatuses != null && bmsDxOrderStatuses.size() > 0){
            for(BmsDxOrderStatus bmsDxOrderStatus : bmsDxOrderStatuses){
                String redisKey = Constants.REDIS_KEY_PREFIX + "refund:" + bmsDxOrderStatus.getOrderId();
                boolean ret = RedisDistributedLockUtils.tryLock(redisKey, TimeUnit.SECONDS,1L);
                if(ret) {
                    //再次确认是否已经被退款了
                    bmsDxOrderStatus = bmsDxOrderStatusService.getBaseDao().findByOrderIdAndStatus(bmsDxOrderStatus.getOrderId(),Constants.REFUND_ING);
                    if(bmsDxOrderStatus == null){
                        continue;
                    }
                    log.info("定时退款开始，退款订单id : " + bmsDxOrderStatus.getOrderId());
                    try {
                        Integer orderId = bmsDxOrderStatus.getOrderId();
                        BmsDxOrder bmsDxOrder = bmsDxOrderService.getBaseDao().findByIdAndIsDelete(orderId, Constants.COMMON_FLAG_FALSE_INT);
                        if(bmsDxOrder == null){
                            return;
                        }
                        BmsDxGroupBuy bmsDxGroupBuy = bmsDxOrder.getBmsDxGroupBuy();
                        conditionMap.clear();
                        conditionMap.put("isRefund",Constants.COMMON_FLAG_TRUE_INT);
                        conditionMap.put("refundResult",Constants.REFUND_IMG);
                        conditionMap.put("orderId",orderId);
                        //查询所有退款中的券码
                        List<BmsDxGroupBuyUse> bys = bmsDxGroupBuyUseService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
                        if(!(bys != null && bys.size() > 0)){
                            return;
                        }
                        //将订单进行归类
                        Map<String,List<BmsDxGroupBuyUse>> bmsDxGroupBuyUsesMap = new HashMap<>();
                        for(BmsDxGroupBuyUse bmsDxGroupBuyUse : bys){
                            String refundTime = DateTimeUtils.converDateToString(bmsDxGroupBuyUse.getCommitTime(),DateTimeUtils.DATE_PATTERN_TIMESTAMP_03);
                            if(!bmsDxGroupBuyUsesMap.containsKey(refundTime)){
                                bmsDxGroupBuyUsesMap.put(refundTime,new ArrayList<>());
                            }
                            bmsDxGroupBuyUsesMap.get(refundTime).add(bmsDxGroupBuyUse);
                        }
                        if(bmsDxGroupBuyUsesMap.size() > 0){
                            if(bmsDxGroupBuyUsesMap.size() > 0){
                                for(Map.Entry<String,List<BmsDxGroupBuyUse>> entry : bmsDxGroupBuyUsesMap.entrySet()){
                                    List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = entry.getValue();
                                    bmsDxOrderService.orderRefundHandle(bmsDxOrder,bmsDxOrderStatus,
                                            bmsDxGroupBuy,bmsDxGroupBuyUses);
                                }
                            }
                        }
                    }catch (Exception e){
                        log.error("refund error",e);
                    }finally {
                        RedisDistributedLockUtils.unlock(redisKey);
                    }
                }
            }
        }
    }

    public void updateOrderBusinessName(BmsBusiness bmsBusiness) {
        List<BmsDxOrderStatus> bmsDxOrderStatuses = bmsDxOrderStatusService.findByBusinessId(bmsBusiness.getId());
        if(CollectionUtils.isNotEmpty(bmsDxOrderStatuses)){
            bmsDxOrderStatuses.forEach(bd -> {
                bd.setVendorName(bmsBusiness.getVendorName());
            });
            bmsDxOrderStatusService.getBaseDao().saveAll(bmsDxOrderStatuses);
        }
        List<BmsDxOrder> bmsDxOrders = bmsDxOrderDao.findByBmsBusinessId(bmsBusiness.getId());
        if(CollectionUtils.isNotEmpty(bmsDxOrders)){
            bmsDxOrders.forEach(bd -> {
                bd.setVendorName(bmsBusiness.getVendorName());
            });
            bmsDxOrderDao.saveAll(bmsDxOrders);
        }
        RBloomFilter bloomFilter = RedisDistributedLockUtils.redissonClient.getBloomFilter("1233");

    }


}
